質問

I want to change

$('a span:contains("myText")').click();

to

var ev = document.createEvent("MouseEvents");
ev.initEvent("click", true, true);
document.querySelector(???).dispatchEvent(ev);

what is ??? should i type?

役に立ちましたか?

解決

unfortunately, what you are asking cannot be done with a single line, as JavaScript does not have a 'contains' selector.

what you must do, is get all the 'a span' elements using document.querySelectorAll() and then iterate through them and check if they contain 'myText' in them.

here is an example FIDDLE

html:

<a href="/three"><span>banana button</span></a>
<a><span>orange button</span></a>

css:

span {
    width:100px;
    height:25px;
    border:2px solid red;
    cursor:pointer;
}

js:

var ev = document.createEvent("MouseEvents");
ev.initEvent("click", true, true);
var all_spans = document.querySelectorAll("a span");
for (i = 0; i < all_spans.length; i++) {
    if (all_spans[i].innerText.indexOf("banana")>-1) {
        all_spans[i].dispatchEvent(ev);
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top