简体   繁体   中英

Javascript, how to select using DOM xpath something between <br> tag

How to select something between <br> tag, using xpath or maybe suggest other solution. so far this is my code where I select the <p> but I need what is between <br> tag:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>some text <br>select this </br>and not this</p>
<div id="insert"></div>
<script>
data = document;
var headings = data.evaluate("//p", data, null, XPathResult.ANY_TYPE, null);
var thisHeading = headings.iterateNext();
var selectedText = "Selected: <br>";
while (thisHeading) {
    selectedText += thisHeading.textContent + "<br>";
    thisHeading = headings.iterateNext();
}
document.getElementById('insert').innerHTML = selectedText;
</script>
</body>
</html>

Assuming <br> is the only tag that will be in p . Youl could split on each <br> tags to get an array of elements.

NOTE: </br> is invalid.

var strings = 'some text <br>select this <br/>and not this'.split(/<br\/?>/i);
alert(strings.length); //3

Well </br> is not valid HTML as the br element is an empty element.

As far as XPath is concerned, you could use the path //p/br[1]/following-sibling::node()[1][self::text()] to select the text node with the string value select this and to select an empty node set in case the following sibling of the first br child is not a text node.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM