0
<div class="class1">
this is string hi hi hi
    <div class="class2">
        hi 
    </div>
</div> 

result: "this is string hi hi hi"

Is it possible to extract a string that does not belong to a tag using only a css selector? Content in class2 should be excluded.

dartman
  • 7
  • 3
  • if you want to hide `.class2` content you can do it by setting it's display to none,`.class2{display: none} ` – Saeed Shamloo Jan 09 '22 at 13:47
  • It's crawling. I want to extract using a selector without touching the document. – dartman Jan 09 '22 at 13:53
  • If you want to extract string and use with something else, then use JavaScript. CSS can show or hide string that is displaying to the web browser. Or if you running it on server side and PHP supported, maybe use PHP `DOMDocument`. – vee Jan 09 '22 at 14:21

2 Answers2

0

It is not good way to put raw text in div in this situation. I recommand you to put span or other inline tags and then put your string in it, then the problem will get much easier.

If you want to extract only string in this situation, you can use textContent property.

const class1 = document.getElementsByClassName('class1')[0]
const class2 = document.getElementsByClassName('class2')[0]
const text1 = class1.textContent
const text2 = class2.textContent
console.log(text1.substr(0, text1.lastIndexOf(text2)))
<div class="class1">
this is string hi hi hi
    <div class="class2">
        hi 
    </div>
</div>
Jello
  • 334
  • 2
  • 10
0

I have come up with a solution. You need to touch the document, but it won't affect the document actually because what I do here will be done in backend.

let newElementStr = class1.innerHTML;//Get the content of Class 1 including Class 2
//Create a duplicate of Class 1 Element and hide it.
let newElement = document.createElement('div');
newElement.style.display = 'none';
newElement.innerHTML = newElementStr;
newElement.id = 'new-el';
//Remove the Class 2 Element
let class2Element = document.querySelector('#new-el .class2');
document.remove(class2Element);
let content = newElement.innerHTML;//This is the string you want
document.remove(newElement);//Cleaning up

You don't need to worry about touching the document because all the changes made by this code won't affect the document because they are hidden display: none;

Hope it works for you!

Satyam Mishra
  • 169
  • 1
  • 9