Checking if a value from window.getSelection matches a string

时间:2016-07-11 21:31:26

标签: javascript jquery

I am working on a text editor but want to do an action when someone starts to type inside a paragraph tag that contains an image or has a certain class.

Using:

sel = window.getSelection();
var p = sel.baseNode.parentNode;

I can console.log p and see as an example:

<p>this is a paragraph</p>

However, when ever I try to check the 'p' var against anything in a if statement it doesn't match. Niether does indexOf as it says indexOf is not a function of p.

Any help?

Specifically, looking to check if the p var string contains class="has-image"

2 个答案:

答案 0 :(得分:0)

Sorry I deleted my last Answer, because I misunderstood your problem. This is the solution:

You are looking for the sel.baseNode.parentNode.nodeName

And to check the class: sel.baseNode.parentNode.className

答案 1 :(得分:0)

Use the jQuery hasClass() function.

$(p).hasClass("has-image")