Question

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?

Was it helpful?

Solution

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);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top