This question already has answers here:
previousSibling not working
(2 answers)
Closed 6 years ago.
this is demo code so I want only follow the pattern that when user click button it show inner text of anchor in h3 tag .
My Code
var a = document.getElementById('btn');
var b = a.previousSibling.firstChild.innerText;
alert(b);
<div class="box">
<p>This is a paragraph</p>
<h3> Heading </h3>
<button id="btn">Click Me</button>
</div>
I am getting this :
Error is Cannot read property 'innerText' of null
you need to use previousElementSibling instead
var a = document.getElementById('btn');
var b = a.previousElementSibling.firstChild.innerText;
console.log(b);
<div class="box">
<p>This is a paragraph</p>
<h3>Heading</h3>
<button id="btn">Click Me</button>
</div>
Try this,
<div class="box">
<p>This is a paragraph</p>
<h3>Heading</h3>
<button id="btn">Click Me</button>
</div>
var a = document.getElementById('btn') ;
var b = a.previousElementSibling.firstChild.innerText ;
alert(b);
I got your sample working in a fiddle here by eliminating whitespace between the button and the closing </h3> tag: https://jsfiddle.net/shggo1x4/
<div class="box">
<p> This is a paragraph </p><h3> Heading </h3><button id="btn"> Click Me</button>
</div>
var a = document.getElementById('btn') ;
var b = a.previousSibling.firstChild.innerText;
alert(b) ;
previousSibling considers whitespace to be a text node, so as #dippas said, use the previousElementSibling property.
Related
I want to get the text of the paragraph (p) contained in div by clicking on that div using the class name. I tried using innerText and innerHTML but it returns undefined in the console. How can I do it using only Javascript?
HTML
<div class="showName">
<p class="paragraphs">Text 1</p>
</div>
<div class="showName">
<p class="paragraphs">Text 2</p>
</div>
<div class="showName">
<p class="paragraphs">Text 3</p>
</div>
Javascript
const showName = document.getElementsByClassName('showName');
const paragraphs = document.getElementsByClassName('paragraphs');
Array.prototype.forEach.call(showName, function(element) {
element.addEventListener('click', function() {
// How can I do it here?
});
});
Working example: https://codepen.io/shinaBR2/pen/qBbxRgz
Basic code is
Array.prototype.forEach.call(showName, function(element) {
element.addEventListener('click', function() {
// How can I do it here?
const text = element.querySelector('.paragraphs').textContent;
alert(text);
});
});
If you want to get text inside all the paragraphs having "paragraphs" class, this code can also help you:
HTML
<div class="showName">
<p class="paragraphs">Text 1</p>
</div>
<div class="showName">
<p class="paragraphs">Text 2</p>
</div>
<div class="showName">
<p class="paragraphs">Text 3</p>
</div>
JAVASCRIPT
const showName = document.getElementsByClassName('showName');
const paragraphs = document.getElementsByClassName('paragraphs');
for(i=0; i < paragraphs.length; i++){
console.log(paragraphs[i].innerText);
}
I'm just starting learning Javascript, and right now I'm on document.createElement. I understood that you can create a HTML tag this way, and that afterwards you have to put it into a HTML tag that already exists (parent). My question is Can I choose exactly where I put this created HTML tag in the parent tag ?
Let's say for exemple I have the following HTML :
<div id="parent">
<div>
<p>First paragraph</p>
</div>
<p>Second paragraph</p>
<p>Third paragraph</p>
</div>
And this javascript :
const getMyDiv = document.getElementById("parent");
const createParagraph = document.createElement("p");
getMyDiv.appendChild(createParagraph);
I will have the following result :
<div id="parent">
<div>
<p>First paragraph</p>
</div>
<p>Second paragraph</p>
<p>Third paragraph</p>
<p></p>
</div>
So what i'm asking is how can I create this <p> at a different position, for exemple like this :
<div id="parent">
<div>
<p>First paragraph</p>
</div>
<p>Second paragraph</p>
<p></p>
<p>Third paragraph</p>
</div>
.appendChild(), indeed append your created element at the end of the list of the children of your selected element, as you demonstrated.
Though, there are other methods that can be used, based on your needs, so you can mount your element wherever you want e.g. .insertBefore() or .prepend()
There are some differences on how they work, so I suggest you take a look on the provided links so you can understand the differences.
You can use this script if you want to place the position to a specific location
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
</style>
<script language="javascript">
function myFunction(){
//var getMyDiv = document.getElementById("parent");
//var createParagraph = document.createElement("p");
//getMyDiv.appendChild(createParagraph);
var child = document.createElement('p')
var parent = document.getElementById("parent");
parent.insertChildAtIndex(child, 2)
}
Element.prototype.insertChildAtIndex = function(child, index) {
if (!index) index = 0
if (index >= this.children.length) {
this.appendChild(child)
} else {
this.insertBefore(child, this.children[index])
}
}
</script>
<button onclick="myFunction()">Try it</button>
<div id="parent" style="background-color:red;width=100px;height:100px">
<div>
<p>First paragraph</p>
</div>
<p>Second paragraph</p>
<p>Third paragraph</p>
</div>
to check save as html file and look at the inspection element in the browser
This question already has answers here:
JS get the clicked element with event.target
(4 answers)
Getting the parent div of element
(7 answers)
Closed 3 years ago.
I am struggling to get the parent of button when it is clicked. This is my HTML structure:
<p><button class="remove">x</button> Hamlet<input value="5"></p>
I don't want to use the ID in button because I have many of the same buttons. Any help is appreciated. Thanks!!!
Like this? Note I delegate from a container
document.getElementById("container").addEventListener("click", function(e) {
let tgt = e.target;
if (tgt.classList.contains("remove")) tgt.closest("p").remove();
})
<div id="container">
<p><button class="remove">x</button> Hamlet<input value="1"></p>
<p><button class="remove">x</button> Ophelia<input value="2"></p>
<p><button class="remove">x</button> Polonius<input value="3"></p>
</div>
For browser that doe not like closest you can use tgt.parentElement.remove()
Maybe consider adding a universal click event to all buttons.
const onClickButton = function () {
// The parent element
const parent = this.parentElement;
parent.style.backgroundColor = 'red';
};
[...document.getElementsByTagName('button')].forEach(button => button.addEventListener('click', onClickButton));
<p>
<button class="remove">x</button>
Hamlet1
<input value="5">
</p>
<p>
<button class="remove">x</button>
Hamlet2
<input value="5">
</p>
<p>
<button class="remove">x</button>
Hamlet3
<input value="5">
</p>
I have some tag with same class , i want get each their value and append it to a div how to do it
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>
for (i=1;i<$(".adr").length;i++) {
$("#test").append($(".adr").html() + "</br>");
}
the result :
location1
location1
location1
location1
it seems did apppend 4 times first class, how to get 1 and 2 and 3 and 4 ?
Use each in jquery to get text of all adr class . Do not append line by line as it takes more execution time.Try to append as a whole, Hope this helps
var str=''
$('.adr').each(function(e){
str+=$(this).text()+ "<br>"
})
$("#test").html(str)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>
<div id =test></div>
$('#test').append($('.adr').clone());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>
<div id="test"></div>
You can append all matched elements with .adr using append(). But only this would technically add the original elements and strip from it where it was previously situated in the DOM. So, clone() them to create a new copy of all elements and preserve it's previous state as well.
var rows = $(".adr");
for (var i = 0; i < rows.length; i++) {
$("#test").append($(rows[i]).html() + "<br>")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>
<div id =test></div>
$('.something') returns an array, so you need $('.something')[i] to get each item from the array.
You're calling three jQuery functions for every iteration of the loop - inefficient. Call them once each before the loop, assigning them to a variable, then use the variable instead of the jQuery calls.
You can use each() method. Secondly selecting "#test" and ".adr" is a bad idea declare them as global variable and use them.
let elms = $(".adr");
let test = $('#test');
elms.each(function(){
test.append($(this).html() + "<br>")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>
<div id="test">
</div>
Using querySelectorAll() and map()
document.querySelector('#test').innerHTML = [...document.querySelectorAll('.adr')].map(x => x.innerHTML).join("<br>")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>
<div id="test">
</div>
I'm trying to get it so that each time the randomise button is hit, a new div's inner HTML is displayed - however I get the error message in the Javascript console 'cannot set property'. Can somebody explain what this means and what I'm doing to cause it?
<h1>Test</h1>
<div id="quote1">this is quote number 1</div>
<p id="quote 2">this is quote number 2</p>
<div id="quote 3">this is quote number 3</div>
<button id="button1">Randomise</button>
<script type="text/javascript">
var but = document.getElementById('button1');
but.onclick = function() {
document.getElementById("quote1").innerHTML = "hi";
document.getElementById("quote2").innerHTML = "ho";
}
That because the id is quote 2 and not quote2 i.e you have extra space in between quote 2 and quote 3
Change to
<p id="quote2">this is quote number 2</p>
<h1>Test</h1>
<div id="quote1">this is quote number 1</div>
<p id="quote2">this is quote number 2</p>
<div id="quote3">this is quote number 3</div>
<button id="button1">Randomise</button>
<script type="text/javascript">
var but = document.getElementById('button1');
but.onclick = function() {
document.getElementById("quote1").innerHTML = "hi";
document.getElementById("quote2").innerHTML = "ho";
}
</script>
your id is set to "quote 2" but you're referencing it as "quote2". It displays "cannot set property" because it cannot find any element referenced as "quote2". Change your id to "quote2". And same for "quote3"
This should work
<h1>Test</h1>
<div id="quote1">this is quote number 1</div>
<p id="quote2">this is quote number 2</p>
<div id="quote3">this is quote number 3</div>
<button id="button1">Randomise</button>
<script type="text/javascript">
var but = document.getElementById('button1');
but.onclick = function() {
document.getElementById("quote1").innerHTML = "hi";
document.getElementById("quote2").innerHTML = "ho";
}
</script>