Select div with a text inside in JS - javascript

I want to modify a div with a special text inside like this.
<div>
<p>
A global issue
</p>
</div>
How can I get it in JS without using id or class ? And only the div with the text "A global issue".
Is there a way to do it?

To target the div and set it to display: none you can run either:
// Pure JS
document.querySelector("div p").style.display = "none"
// w/jQuery
$('div p').hide();
If there's more then one div p tags in your HTML, you can also search by text using the following:
$('div p:contains("A global issue")').css('display', 'none');

If you want to use simple javascript solution, see snippet below
First, get all divs from page
Second, store your search text in a variable
Third, loop through all divs and find the one containing your text, then you can do whatever you want with it. I added a backgroundColor red to it
var divs = document.querySelectorAll("div");
var myText = "A global issue";
var i;
for (i = 0; i < divs.length; i++) {
if (divs[i].textContent.indexOf(myText) > 0 ) {
divs[i].style.backgroundColor = "red";
}
}
<div>
<p>
A global issue
</p>
<p>
More text here
</p>
</div>
<div>
<p>
Not a good text
</p>
</div>

You can use jquery:
$('div:contains("A global issue")').css('background-color', 'red');
<div>A global issue</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

let i=5;
let divs =Array.from( document.querySelectorAll('div > p')); // it returns array
divs[i].style.display= "none";
Edit:
for(let i=0;i<divs.length;i++){ if(divs[i].textContent==="some text"){ divs[i].style.display="none"; } }
if you want to change parent node do divs[i].parentNode.style.display="none"

Related

How to access a <p> inside three layers of <div> using Javascript?

I'm trying to use Javascript so that a paragraph will alternate between two texts when the user presses a button on the webpage. The problem is that the <p> element I'm trying to manipulate lies within a <div> within a <div> within a <div>.
A low-level mockup of my code can be seen below:
<div id="div1">
<div id="div2">
<div id="div3">
<p>text1</p>
</div>
</div>
</div>
All solutions I've found only state what to do if the <p> is within one <div>; solutions which have not worked for me.
Here's my latest attempt:
function translate() {
var x = document.getElementById("div1").getElementById("div2").getElementById("div3").getElementsByTagName('p')[0];
if (x.innerHTML === "text1") {
x.innerHTML = "text2";
} else {
x.innerHTML = "text1";
}
}
How would I get this to work?
Edit: Nothing seems to be working so far. The <div> element all have classes, but that shouldn't affect things, right?
Edit2: My apologies for taking up your time, but I've found the issue was something else entirely. I'd been using a reserved word for my function call this whole time and had somehow never noticed that that was the issue instead. Thanks again to those who answered, and I shall look deeper at my code before posting my next question.
Why not just use
var x = document.getElementById("div3")
If accessing by the Id directly, it does not really matter what the other DIVs are.
If divs are always in that order, you can do it like this:
var x = document.querySelector('#div1 #div2 #div3 p');
You can use document.querySelectorAll to get an array of all p tags on the page.
const pTags = document.querySelectorAll('p')
pTags.forEach((p, i) => {
if(i % 2 === 0) {
p.innerHTML = 'text1'
} else {
p.innerHTML = 'text2'
}
})
Instead of Ids, you can be more specific & try the following:
var x = document.querySelector('div > div > div > p')
This will be a very strict implementation & follows the condition without the ids or classes.
Use querySelector in order to use the CSS selector #div3 p which means "pick up the paragraph element that is inside the element that has a div3 id".
Then, as you're just changing a string of text, change either the textContent of that element, or its innerText (there are subtle differences between them.)
const para = document.querySelector('#div3 p');
const button = document.querySelector('button');
button.addEventListener('click', translate);
function translate() {
if (para.textContent === 'text1') {
para.textContent = 'text2';
} else {
para.textContent = 'text1';
}
}
<div id="div1">
<div id="div2">
<div id="div3">
<p>text1</p>
</div>
</div>
</div>
<button type="button">Translate</button>

How to change the color of all paragraphs (not the headings) on click of a button?

I'm using JavaScript and having trouble getting my function to work. I'm trying to change the color of all my paragraphs using a button click, but I haven't managed to achieve it. I have already managed to change the background color with the same button.
This is the function I used to change the paragraphs color:
function color() {
document.getElementById("changecolor").style.color = "blue";
}
I used an id changecolor on all my paragraphs as well, but doesn't work.
I used an id "changecolor" on all my paragraphs as well but doesn't
work.
If you're trying to change the background colour of all paragraphs, they should be identified using a Class -- not an ID. If you try to change the CSS of something with a ID, you'll only affect one of the elements on the page with that ID. Classes are meant to be used multiple times through out the page, as opposed to IDs which are meant to be uniqued and, therefore, only used once.
So, if you have a bunch of paragraphs called zalachenka for example, they'd look like this:
<p class="zalachenka">Here's my paragraph text where I want to change the background colour</p>
<p class="zalachenka">Here's my paragraph text where I want to change the background colour</p>
<p class="zalachenka">Here's my paragraph text where I want to change the background colour</p>
You could use getElementsByClassName to find all of these Classes, but that would generate an array of results and you would have to loop through them to assign the colours. To target the first element, you'd have to write your JavaScript like this:
document.getElementsByClassName('zalachenka')[0].style.backgroundColor = 'blue'
Since you have three (in the above example), you would have to loop through all of them.
const elems = document.getElementsByClassName('zalachenka') // returns array of elements.
for (let i = 0; i < elems.length; i++) {
elems[i].style.backgroundColor = 'blue' // loops through the array and assigns the background color to each element.
}
Keep in mind, this will assign CSS to the Tag inline. When the process is complete, the HTML will looks like this:
<p class="zalachenka" style="background-color: red;">Here's my paragraph text where I want to change the background colour</p>
<p class="zalachenka" style="background-color: red;">Here's my paragraph text where I want to change the background colour</p>
<p class="zalachenka" style="background-color: red;">Here's my paragraph text where I want to change the background colour</p>
Your code is fine except the Id part. Just replace the 'getElementById' by 'getElementsByClassName' and give all the paragraph a common class name.
For Ex... class='common-paragraph'.
If you give the same id to all the paragraphs then it won't work as Id should be unique. You won't get any error for this in HTML or JS.
First, you need to select all the p elements
You can use either
const ps = Array.from(document.querySelectorAll('p')) // string can be any CSS selector
or
const ps = Array.from(document.getElementsByTagName('p')) // might be a bit faster
then
for (let i = 0; i < ps.length; i++) {
ps[i].style.color = 'green'
}
note:
let and const are replacement for the var keyword, but you can avoid some strange bugs caused by var
note2:
most HTML request doesn't return the type you expect,
<input type="number" > still returns a string as its value
and document.getElementsByTagName returns an array like object, which looks like this:
{
length: 2,
0: foo,
1: bar
}
To convert it to an array use Array.from(arrayLike)
you can use class, since id should be unique why id should be unique . Also you can get all the elements by using getElementsByClassName. Which will be a collection so you can use for loop and iterate through each element and change the color.
I hope this will solve the issue
function color() {
var elements = document.getElementsByClassName("changecolor");
for (var i = 0; i < elements.length; i++) {
elements[i].style.color = "blue";
}
};
<p class="changecolor">First Paragraph</p>
<p class="changecolor">Second Paragraph</p>
<p class="changecolor">Third Paragraph</p>
<button onclick="color()">Changing Color Button</button>
If you want to apply style to all p tags, you can use javascript's getElementsByTagName to select all elements of a given tag name.
So your javascript code would go like this
function color() {
var paragraphs = document.getElementsByTagName("p");
var i;
for (i = 0; i < paragraphs.length; i++) {
paragraphs[i].style.color = "blue";
}
};
In case there is a style sheet or script that is already applying a color style, you could use javascripts !important keyword against your style.. in that case the code would get modified like this..
function color() {
var paragraphs = document.getElementsByTagName("p");
var i;
for (i = 0; i < paragraphs.length; i++) {
paragraphs[i].style = "color: blue !important";
}
};
To apply on a single id you would write like this
document.getElementById("changecolor").style = "color:blue !important;";
Please note that an id attribute must be unique per DOM document. If you apply same id attribute to multiple elements, a warning would appear and document.getElementById("") would return the first element that matched the id.
Thanx.
You can't use id for multiple tags in HTML
id for each tag should be uniq
You should use class instead of id
You can do this (Changing Color Using Tag Name):
<p>This is a Paragraph</p>
<p>This is a Paragraph</p>
<p>This is a Paragraph</p>
<button onclick="MakeChanges()">Change Styles</button>
<script>
function MakeChanges() {
const MyCollection = document.getElementsByTagName('p')
for (let i = 0; i < MyCollection.length; i++) {
MyCollection[i].style.color = "blue"
}
}
</script>
Or This (Changing Color Using Class Name):
<p class="changecolor">This is a Paragraph</p>
<p class="changecolor">This is a Paragraph</p>
<p class="changecolor">This is a Paragraph</p>
<button onclick="MakeChanges()">Change Styles</button>
<script>
function MakeChanges() {
const pTags = document.getElementsByClassName('changecolor')
for (let i = 0; i < MyCollection.length; i++) {
MyCollection[i].style.color = "blue"
}
}
</script>

efficient way to remove empty div

I'm using <div contenteditable="true">, when I press enter to newline with empty input, it will generate <div><br></div>.
But I just want to remove it from beginning and at the end.
For example:
<div contenteditable="true">
<div><br></div> i want to remove this
abc
<div><br></div> remain
1234
<div><br></div> i want to remove this
<div><br></div> i want to remove this
</div>
for(var x = item.length - 1 ; x >= 0 ; x--){
if($(item[x]).html() == "<br>"){
$(item[x]).remove();
}else{
break;
}
}
for(var x = 0; x <= item.length-1 ; x++){
if($(item[x]).html() == "<br>"){
$(item[x]).remove();
}else{
break;
}
}
Currently I'm using two looping to remove it, But I'm looking a better way to filter it.
Anyone can guide me?
Thanks.
You can actually achieve it with while loop instead of for loop. You need to store the reference for first and last child of the contenteditable div and manipulate it with while loop. Detailed explanation in comments around the code.
$('.remove').on('click', function() {
var firstChild = $('div[contenteditable] div:first');
var lastChild = $('div[contenteditable] div:last');
//store the reference for first and last child of the contenteditable div
while(firstChild.html()=="<br>")//remove all the element's until firstchild's html!="<br>" i.e. is not empty
{
firstChild.remove();//remove it
firstChild= $('div[contenteditable] div:first'); //again store the reference to new first child after remove
}
//same goes with last child
while(lastChild.html()=="<br>")
{
lastChild.remove();
lastChild= $('div[contenteditable] div:last');
}
})
div[contenteditable] {
background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true">
</div>
<button type="button" class="remove">Remove unwanted</button>
If you want to remove a div which is empty..(Your question states that)....
This may help.....
$("div:empty").remove();
This code removes div that are empty...If thats what You wanted this could help

Best way to show all hidden divs in javascript

I have several hidden divs inside large div, they can be shown one by one or all at once
It looks like this:
<div class="maindiv">
Print "<a href=javascript:show()>Click here to show all</a>
Show/hide div1
<div id="div1" style="display:none;">.....</div>
Show/hide div2
<div id="div2" style="display:none;">.....</div>
....
</div>
showhide() function is ok showing/hiding given div, show() works too but like this:
function show(){
div1.style.display="block";
div2.style.display="block";
...
}
so if I'll have 100 divs I'll have to enter it there 100 times
so my question is, how can I find all hidden divs in div with class maindiv and show em other way than enumerate? Or is the way I do ok?
Try using a generic css class name that is defined similarly:
.hidden{
display:none;
}
Then all you have to do is select the elements that have that class and remove that class. Assuming you are using at least IE9 you can try:
var divs = document.getElementsByClassName("hidden");
for(var i = 0; i < divs.length; i++)
{
divs[i].className = ""; //assuming you only have that class set else you will need to do a search and replace
}
If you have to support earlier versions there are other methods that will work to gather all the divs you need such as document.getElementsByTagName("div")
LIVE DEMO
Try this:
JQuery
$('.maindiv div a').click(function(){
$(this).next().toggle();
});
$('#showAll').click(function(){
$('.maindiv div div').show();
});
HTML
<div class="maindiv">
Click here to show all
<div>
Show/hide div1
<div>.....</div>
Show/hide div2
<div>.....</div>
</div>
</div>
CSS
.maindiv div a{
display:block;
}
.maindiv div div{
display:none;
}
Please try with the below code snippet.
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++){
//You can also write here if condition
divs[i].style.display = "block";
}
I think this can work
http://jsfiddle.net/rtu75/
function show() {
var divs = document.getElementsByClassName("maindiv");
var l = divs.length;
for( var i = 0; i < l; i++) {
divs[i].setAttribute("class", "show");
}
}
In your css
.show div {
display: block !important;
}
Added important since you have inline styles
Using jQuery, try
$("*").show();
or
$(parentElem).find("*").show();
or
$(":not(:visible)").show();
// This selects "*". Not I expected.
See w3 - css selectors, MDN - css pseudo classes, and jQuery $(), $().find(), $().filter() methods.
As I saw your code below, I saw it's almost work. You need to change id='div1' to class='hid' after that read my below step >> Go down
Show/hide div1
<div id="div1" style="display:none;">.....</div>
Here is my step, I am in same problem but now I can solve this because I read https://stackoverflow.com/a/24192071/10618118 then try to solve until done.
Read below,it's my code.It's work as I want.
in My Style for CSS be like this
<style>
.hid {}
</style>
Next is My Button to control it hidden or visible, Simple.
<button id="see" type="button" onclick="clickSee();">Show More ...</button>
Next step, look at my Javascript Code below,
I use JQuery 3.2.1 to change function in onclick of button.
when user want to hide or see more
just click Show More ... or ... Show less,
Actually it's the same button but user don't know.
If you didn't use JQuery yet and decide to use just copy
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
and paste in <head></head>
<script>
function clickSee() {
document.getElementById("see").innerHTML = "... Show Less";
var divs = document.getElementsByClassName("hid");
for (var i = 0; i < divs.length; i++){
divs[i].style.display = "block";
}
//I use JQuery
$("#see").attr("onclick", "clickHide()");
}
function clickHide() {
document.getElementById("see").innerHTML = "Show More ... ";
var divs = document.getElementsByClassName("hid");
for (var i = 0; i < divs.length; i++){
divs[i].style.display = "none";
}
//I use JQuery
$("#see").attr("onclick", "clickSee()");
}
</script>
If you have any issues just comment below, I will try to help because when done.
There are many way to make your idea work. but I see here is my basic way.
Feel free for new recommendation. Thank you.

Display none to All div by loop and display a perticular div which I want to show

I am using Javascrip and I have a function like the following where I want to hide all div. But I don't know why this code is not working. Will anyone help me with this?
Javasvript
function showDiv(divTag,id)
{
var i;
for(i=1;i<7;i++)
{
document.getElementById(divTag+i).style.display = 'none';
}
document.getElementById(divTag+id).style.display = 'block';
}
or
function showDiv(divTag,id)
{
var i;
for(i=1;i<5;i++)
{
var tempDiv = divTag + i;
document.getElementById(tempDiv).style.display = 'none';
}
document.getElementById(divTag+id).style.display = 'block';
}
And HTML
Show Only Div1
<div id="hide_1">
Abc
</div>
Show Only Div2
<div id="hide_2">
BCD
</div>
Show Only Div2
<div id="hide_3">
EDF
</div>
Show Only Div2
<div id="hide_4">
FGE
</div>
Both of the abov process I have tried but failed to do that
Several things:
The "onclick" (not "onClick") is the correct way to assign the click event handler in both html and JavaScript.
You are looping from 1 to 6 in for(i=1;i<7;i++) line of the first function, but you only have 4 elements in your html. When reaching the non-existing fifth - your code will throw an error. Something along the lines of "TypeError: Cannot read property 'style' of null".
As #verisimilitude has mentioned, you have a syntax error in your html where you put a quoted text inside another text that's quoted in the same way. It should be onclick="showDiv('hide_',1)". Note the single quotes around 'hide_'.
Here's the code that works. Click here to see it in action.
Here's your JavaScript function:
// Please note that it must be in the global scope
// otherwise you won't be able to call it from your html.
function showDiv(divTag, id) {
var i;
for (i = 1; i < 5; i++) {
var tempDiv = divTag + i;
document.getElementById(tempDiv).style.display = 'none';
}
document.getElementById(divTag+id).style.display = 'block';
}
Also, take a look at another working version of your code that pre-validates the existence of your elements before hiding/showing them. So you don't have to worry about your for loop iterating over elements that have been removed.
And here's your html:
Show Only Div1
<div id="hide_1">Div1</div>
Show Only Div2
<div id="hide_2">Div2</div>
Show Only Div3
<div id="hide_3">Div3</div>
Show Only Div4
<div id="hide_4">Div4</div>​
Show Only Div1
yields a javascript syntax error. This should be
Show Only Div1
Check the single quotes around "hide_"

Categories

Resources