Find an element that contain certain character using javascript - javascript

i want to detect the parent of element that has "_" character in it
that could be achieved using jquery and css3 selcetor ":contain" like the following
$('.class a:contains("_")').parent()
but im trying to avoid using jquery too much , so is there any way to do this using native js

There is no CSS to check if it contains text. Only way you can do text matching is if that text happened to be in an attribute on the element. So you are going to have to select all the parent elements and loop over them looping at the text/children's text.
To do that you can select all the elements and use filter to check the text. If you only care there is an underscore you can just text the text content of the element.
const elemsWithUnderscore = [...document.querySelectorAll('.yourClass')].filter(el => el.textContent.includes('_'));
console.log(elemsWithUnderscore);
<div class="yourClass"><a>a</a></div>
<div class="yourClass"><a>b_</a></div>
<div class="yourClass"><a>c</a></div>
<div class="yourClass"><a>d_</a></div>
<div class="yourClass"><a>e</a></div>
If it only can be in the anchor tag and there is one you can selector the anchor tag.
const elemsWithUnderscore = [...document.querySelectorAll('.yourClass')].filter(el => [...el.querySelectorAll('a')].some(a => a.textContent.includes('_')));
console.log(elemsWithUnderscore);
<div class="yourClass">_<a>a</a></div>
<div class="yourClass"><a>b</a><a>b_</a></div>
<div class="yourClass"><a>c</a></div>
<div class="yourClass"><a>d_</a></div>
<div class="yourClass"><a>e</a></div>
If there is more than one anchor as children then you need to use some to see if one of them has an underscore.
const elemsWithUnderscore = [...document.querySelectorAll('.yourClass')].filter(el => el.querySelector('a')?.textContent.includes('_'));
console.log(elemsWithUnderscore);
<div class="yourClass">_<a>a</a></div>
<div class="yourClass"><a>b_</a></div>
<div class="yourClass"><a>c</a></div>
<div class="yourClass"><a>d_</a></div>
<div class="yourClass"><a>e</a></div>

You can use document.querySelectorAll and check the textContent of the children.
[...document.querySelectorAll('.class')].filter(el =>
[...el.querySelectorAll('a')].some(a => a.textContent.includes('_')))
.forEach(el => console.log(el.outerHTML));
<div class="class"><a>_</a></div>
<div class="class">
<div><a>abc_def</a><span>123</span></div>
</div>
<div><a>nothing to see</a></div>

Related

trying to use query selector to select a specific child in a html document

site i am selecting from looks roughly like this
<div class="start-left">
...
<div class="news-post">...</div>
<div class="news-post">...</div>
<!-- want to get this one above -->
<div class="news-post">...</div>
<div class="news-post">...</div>
<div class="news-post">...</div>
<div class="news-post">...</div>
...
</div>
tried this but didnt work on either firefox or chrome
document.querySelector('.start-left div:nth-child(2)')
is this even possible or do i need to rething how i am doing this? I am using puppeteer for a webscraper and need to be able to press a link in a specific news post, e.g the second one
nth-child(n) counts all children of the element, regardless of the type of element (tag name). If there are other elements of different type coming before your target element nth-child will fail to find the correct element and may return null.
However, the selector nth-of-type(n)
matches elements based on their position among siblings of the same
type (tag name)
and ignores elements of a different type.
// nth-child(2) returns null because the 2nd element is not a div
var wrongElement = document.querySelector('.start-left div:nth-child(2)');
// nth-of-type(2) filters using the type of element
var correctElement = document.querySelector('.start-left div:nth-of-type(2)');
console.log('div:nth-child(2): ' + wrongElement);
console.log('div:nth-of-type(2): ' + correctElement.outerHTML);
<div class="start-left">
<p class="news-post">...</p>
<p class="news-post">Not this</p>
<div class="news-post">...</div>
<div class="news-post">This one</div>
<!-- want to get this one above -->
<div class="news-post">...</div>
</div>
You could use your work-around by adding the number of preceding elements to the selector, eg nth-child(4), however, a more robust solution is to use nth-of-type(2).

Javascript return something from replaceWith

I have created a javascript web component where one element is completely replaced with a set of html elements.
To do that I use replaceWith. My problem is that I need to keep track of the new created element. How can I do that? I use vanilla js ES6, not jQuery.
let element = document.querySelector('div');
let another = document.querySelector('h2');
element.replaceWith(another);
<div>
Replace this content
</div>
<h2>Heading 1</h2>
<h2>Heading 2</h2>
<h2>Heading 3</h2>
https://jsfiddle.net/n9q0x86a/1/
I have created a javascript web component where one element is completely replaced with a set of html elements
your statement is wrong, if you want to move all the desired elements in place of <div>. In such case you need to use the querySelectorAll()MDN method. Which in turn will give you I believe exactly what you expect: a collection of all our targeted selectors:
const element = document.querySelector('#replaceMe');
const another = document.querySelectorAll('.moveMe');
element.replaceWith(...another);
console.log("Replaced #%s with %i elements", element.id, another.length);
// let's try to manipulate our stored elements:
[...another].forEach(el => el.style.color = 'red');
<div data-info="This DIV should stay">
<div id="replaceMe" data-info="this DIV should be replaced">
Replace this content
</div>
</div>
<h1 class="moveMe">Heading 1</h2>
<h2 class="moveMe">Heading 2</h2>
<p class="moveMe">Paragraph</p>
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

how to toggle a specific div in javascript

i have dynamic data in my rails view, all divs have the same name; 'allData', which has alot of info, so i have it not displayed, i want to display that specific div and not all divs when i click show, but it shows all divs, i want to be able to show just that target div i clicked
$('.show'').on('click', (event) =>{
$('.allData').toggle();
$(event.currentTarget).closest('.allData').toggle();
})
<div class='eachData'>
<div class='header'>
<div class='show'> show</div>
<div class='numberOfdata'> 100</div>
</div>
<div class='allData; display:none'>
"foobar all data is here"
</div>
</div>
<div class='eachData'>
.......
</div>
<div class='eachData'>
.......
</div>
Your closest call is on the right track but you're not quite using it right. First you want to find the container (.eachData) that contains your <div class="show">, you use closest for that:
let container = $(event.currentTarget).closest('.eachData');
then you search within that container for the .allData you want to toggle by using find:
container.find('.allData').toggle();
So you use closest to go up the node tree and then find to come back down.
BTW, this:
<div class='allData; display:none'>
should be:
<div class="allData" style="display: none">
The class attribute contains CSS class names delimited by whitespace, raw CSS goes in the style attribute and is delimited by semicolons.
Your inline style on the div should be as follows:
<div class="allData" style="display: none">
Then try the following:
$('.show').on('click', function() {
$(document).find('.eachData .allData:visible').hide('fast');
$(this).parent().closest('.allData').show('fast');
});

Jquery select the element h3

How can I select element in this HTML using jquery selectors.
<div class = 'divOne">
</div>
<div class = 'divTwo">
<h3>Title</h3>
</div>
$('.divOne').siblings('.divTwo').children('h3')
$(".divOne") to perform jquery functions on first div
$(".divTwo") to perform jquery functions on second div
$("h3") to perform jquery functions on header element
It's pretty simple to select the h3 element.
But you have to fix your HTML first. While, when writing HTML5, in general it's possible to use single-quotes. But, you have to use them at the start and the end of the value like this: <div class='divOne' /> or <div class="divOne" />
$('.divTwo > h3').css('border', '1px solid red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divOne">
</div>
<div class="divTwo">
<h3>Title</h3>
</div>
You could use the jQuery selector and select h3 with $('h3'). But maybe you have more than one h3-tags in your code.
In that case you could give the h3 a class and select the class with the selector.
Example:
<div class = "divOne">
</div>
<div class = "divTwo">
<h3>Title</h3>
</div>
In this case use: $('h3');
OR
<div class = "divOne">
</div>
<div class = "divTwo">
<h3 class="myClass">Title</h3>
</div>
And in this case you use $('.myClass');
-----------
In the above I explained how you could select an h3-tag, but it does work with all elements ofcourse ;)
I also noticed that you use single quotes and double quotes in your HTML ('divOne")
Do not use both for a single attribute. Just "divOne" or 'divOne'.

How to find element based on data-attribute with this existing JS code example?

I want to target a specified div, but my example for now is only when it has an id.
I want to use pure Javascript
current:
<div id="my_id">hello</div>
<script>
document.getElementById('my_id').insertAdjacentHTML('beforebegin',
'<h3>text</h3>');
</script>
my case:
<div data-foo="bar">hello</div>
<div data-foo="club">hi</div>
How can I target the div that has the bar data-foo attribute ?
You can do this using an attribute selector alongside querySelector:
document.querySelector("div[data-foo='bar']").insertAdjacentHTML('beforebegin',
'<h3>text</h3>');
<div data-foo="bar">hello</div>
<div data-foo="club">hi</div>

Categories

Resources