i'm currently learning javascript and had a question.
I am trying to target only the h1 tag in the div id=title i tried a few ways using this as a reference site amongst others: http://www.ibm.com/developerworks/library/wa-jsanddom-pr/sidefile1.html
but nothing seems to be working, i get back the value "undefined"
esentially what i want to do is only target the h1 and change the text to something else.
how do i do that? is this along the right path or is there a different way to do it?
<div id="title">
<h1>Javascript Lesson 1</h1>
<p>The basics</p>
</div>
<script>
var title = document.getElementById('title');
var titleHeading = title.firstChild;
console.log (title.value);
</script>
any help is greatly appreciated. Thanks.
Take a look at Element.getElementsByTagName.
var titleElement = document.getElementById("title");
var titleChildren = titleElement.getElementsByTagName("H1");
// Do something with children.
// In your example code, you'll only have one element returned
console.log(titleChildren[0].innerHTML);
// To change the text, simply access the innerHTML property
titleChildren[0].innerHTML = "[New Value]"
Here's a working fiddle to play with.
If you know that the h1 you want to modify will always be the first h1 child you could do something like this:
<script>
document.getElementById('title').getElementsByTagName("h1")[0].innerHTML = "New Name";
</script>
The first child of the <div> (in your example) is a text node. Text nodes don't have a value property. Even if you remove the whitespace between the <div> and the <h1> to make it the first child node, the <h1> still doesn't have a value property. What it does have is a child text node with the node value "Javascript Lesson 1".
What you want is to retrieve a reference to that text node, and its value. There are different ways to do this. For instance:
<div id="title">
<h1>Javascript Lesson 1</h1> <!-- White space before <h1> -->
<p>The basics</p>
</div>
<script>
var title = document.getElementById('title');
var titleHeading = title.childNodes[1];
console.log (titleHeading.firstChild.nodeValue);
</script>
or:
<div id="title"
><h1>Javascript Lesson 1</h1> <!-- No white space -->
<p>The basics</p>
</div>
<script>
var title = document.getElementById('title');
var titleHeading = title.firstChild;
console.log (titleHeading.firstChild);
</script>
or:
<div id="title">
<h1>Javascript Lesson 1</h1>
<p>The basics</p>
</div>
<script>
var title = document.getElementById('title');
var titleHeading = title.getElementsByTagName('h1')[0];
console.log (titleHeading.innerHTML);
</script>
or some permutation of the above.
You can get a collection of children back with Document.querySelectorAll(). Here are two examples:
var matches = document.querySelectorAll("iframe[data-src]");
var matches = document.querySelectorAll("div.note, div.alert");
As you can see, it is nearly JQuery like. Notice the comma in the second example. JQuery would use a space there. These examples were taken from developer.mozilla.org.
If you don't want a collection, (if you want a single element) document.querySelector("#myCSSSelector"); is what you want.
Related
I want to use javascript to find and replace a word which has been split in a few tags.
For example, the html code:
<html>
<body>
<div id="page-container">
This is an apple.
<div>
<span>a</span><span>p</span><span>ple</span>.
</div>
</div>
</body>
</html>
And the it looks like below in the web browser:
This is an apple.
apple.
I use this javascript to find and replace the word "apple":
var a = document.getElementById('page-container').innerHTML;
a=a.replace(/apple/g,'pear');
document.getElementById('page-container').innerText=a;
But the result in the web browser is very bad, and all the tags could not work:
This is an pear.
<div>
<span>a</span><span>p</span><span>ple</span>.
</div>
It seems the replace function worked for the first row but cannot recognize the word split in the tags. This is an example, the whole content could be much more complex with more tags like , , not only ... Is there a way to replace only text but keep the original html tag format?
var a = document.getElementById('page-container').textContent;
a = a.replace(/apple/g, 'pear');
var a=a.split('.');
document.getElementById('page-container').innerHTML = `${a[0]}.<br/><span> ${a[1]}
<span>`;
That is because you have nested elements, so when you set innerHTML of the parent div, it treats inner div as text and print it out , try to replace this :
document.getElementById('page-container').innerText=a;
with this :
document.getElementById("page-container").firstChild.innerHTML = a;
So, you target only your first child which is parent div.
Live example:
https://jsbin.com/hujurageya/edit?html,js,output
I have a div tag with class divstudent, lets say this is div1 tag. Now I want to create another div tag div2 dynamically below this div1 tag, not inside of the div1 tag. I want to create outside of div1 tag using javascript. How can I do that?
"div1"
<div class="divstudent"></div>
<!-- i want to be like this -->
<!-- "div1" -->
<div></div>
<!-- "div2" -->
<div></div>
<!-- "div3" -->
<div></div>
$(function() {
$("div").eq(0).after("<div>This is div 2</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
This is div 1
</div>
Try something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Divs creator</title>
<script type="text/javascript">
window.onload = function () {
var divReference = document.querySelector('.divstudent');
var divCounter = 0;
divReference.addEventListener('click', function () {
var divToCreate = document.createElement('div');
divToCreate.innerHTML = ++divCounter;
divReference.parentNode.appendChild(divToCreate);
}, false);
}
</script>
</head>
<body>
<div class="divstudent">
<input type="button" value="add div below divstudent">
</div>
</body>
</html>
Since this is tagged jquery, just use .after()
$(function() {
$("div").eq(0).after("<div>This is div 2</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
This is div 1
</div>
There are many ways to do this. One significant difference in methods is if you choose to create the elements first using Document.createElement() and then insert the elements, or create and insert the elements in one step using one of the methods that allows you to insert HTML text.
Because it is simpler, but not necessarily better, the examples below show creating and inserting the two <div> elements in a single step using methods that allow inserting HTML text into the DOM.
JavaScript:
One is to use insertAdjacentHTML() and specify that it is to be inserted afterend of the element you are using.
document.querySelector() is used to find the first <div class="divstudent">. Then insertAdjacentHTML() is used to add the additional <div> elements. Element.removeAttribute() is then used to remove the class="divstudent". Note: if we had just wanted to set teh class to something different, even '', then we could have used Element.className.
NOTE: In this answer, text identifying each <div> has been added to the <div>s so there is something visible in the examples in this answer.
//Find the first <div class="divstudent"> in the document
var studentDiv = document.querySelector('div.divstudent');
//Insert two new <div> elements.
studentDiv.insertAdjacentHTML('afterend','<div>2</div><div>3</div>');
//Remove the class="divstudent"
studentDiv.removeAttribute('class');
<div class="divstudent">1</div>
jQuery:
While your question is tagged jQuery, a comment you posted implies you are just using JavaScript. Thus, I am not sure if jQuery works for you.
If you want to use jQuery, then you can use .after() to add the <div> elements. You can then use .removeAttr() to remove the class="divstudent".
// Get the first <div class="divstudent">.
// Store it in a variable so we only walk the DOM once.
var $studentDiv = $('div.divstudent').eq(0);
//Add the two new <div> elements
$studentDiv.after('<div>2</div><div>3</div>');
//Remove the class="divstudent"
$studentDiv.removeAttr('class');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divstudent">1</div>
You create a new div (in js), then just append your newDiv, after the target div. Something along the lines of in vanilla js:
// Create your new div
var newDiv = document.createElement("div");
newDiv.innerText = "New Div!";
// Grab the div you want to insert your new div after
var target_div = document.querySelector("div.divstudent");
// Insert newDiv after target_div (before the thing after it)
target_div.parentNode.insertBefore(newDiv, target_div.nextSibling);
I have following paragraph in html code:
<p id=tag1> html statements before click </p>
... and I am trying to write function which would split the above paragraph to two paragraphs like this :
<p id=tag1> html statements after click </p><p id=tag2></p>
... with intention to exchange then tag1 id with tag2 id to have final result:
<p id=tag2> html statements after click </p><p id=tag1></p>
I am trying to achieve desired result by this function:
<script>
function myFunction() {
document.getElementById("tag1").innerHTML = "html statements after click </p><p id='tag2'>";
document.getElementById("tag2").id = "tagTmp";
document.getElementById("tag1").id = "tag2";
document.getElementById("tagTmp").id = "tag1";
}
</script>
... but this donesn't work to me. Problem is with the first step - innerHtml modification works different ways as expected and yealds following result:
<p id=tag1> html statements after click
<p></p>
<p id=tag2></p>
</p>
... paragraph id=tag2 is still nested inside paragraph id=tag1 (I want to have the both paragraphs at the same level).
Is there any way to get requested functionality? Can you help please?
Thanks.
document.getElementById("tag1").innerHTML = "html statements after click </p><p id='tag2'>";
So the reason this is not acting as you expect it to is because this is not changing the markup, as you think it is. innerHTML does not include the open and close tags. Your interacting with a dom node, so you can't close the parent node like that. As you can see it tries to protect your weird request of a single </p> and creates a new open for it so it's paired.
If you were going to do this with jquery, as that's one of your post tags, it could possibly be something like...
//get the existing element
var $originalTag = $('#tag1');
//update its id
$originalTag.prop('id', 'tag2');
//create a new one after it with the original id
$('<p id="tag1"></p>').insertAfter($originalTag);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="tag1">An Existing Tag</p>
Here is a sample code for you
<html>
<div>
<p id=tag1> html statements before click </p>
</div>
<script>
var
p = document.querySelector('p'),
p2 = document.createElement('p');
p2.id = 'p2';
p2.textContent = ' p2...p2 '
p.outerHTML += p2.outerHTML;
</script>
</html>
My code is pretty much explain itself of what I'm about to get :
<div id=player>
<div class="button hand">►</div>
<div class=time>00:00/02:25</div>
<div class="timeline hand"><span class="now hand"></span></div>
</div>
<script>
var myPlayer=document.getElementById('player').firstChild;
var playerStatus=(myPlayer.innerText||myPlayer.textContent);
console.log(playerStatus);
</script>
I'm expect to get the ascii value ► on console.
Small tweak needed here
Try this:
var myPlayer=document.getElementById('player').firstElementChild;
The problem is that the first child of #player is a text node itself. What you're looking for is the first element child of #player.
A minor note: firstElementChild isn't supported by IE8-.
You have both id and class available, so use querySelector().
var myPlayer=document.querySelector('#player > .button.hand');
This also has the benefit of working in IE8.
Also, a shortcut for innerText/textContent is to check for it at the top of your script, and store the appropriate key in a string.
var text = ("textContent" in document) ? "textContent" : "innerText";
Then use square brackets with the text variable.
var myPlayer=document.querySelector('#player > .button.hand');
var playerStatus=(myPlayer[text]);
Then you can actually shorten it like this:
var playerStatus=document.querySelector('#player > .button.hand')[text];
I would like to know how to remove all the HTML between two strings in a webpage. The webpage will not always have the same content, so this must work no matter what the two strings are and what their positions are. For example,
<div class='foo'>
<div class='userid'>123</div>
<div class='content'>
asdfasdf
</div>
</div>
<div class=bar>
<div class='userid'>456</div>
<div class='content'>
qwerqwer
</div>
</div>
How could I remove all the HTML between 'asdfasdf' and '123'?
Thanks
This is ugly but it works:
var container = $("#cont");
var text = container.html();
var arr = text.split("asdfasdf");
arr[1] = "";
arr = arr.join("");
$("#cont").html(arr);
I added a container div. You could use the body tag or something else. Its possible with a regex as well.
Here is a working demo http://jsfiddle.net/QJSJH/.
Edit
I see the post changed quite a bit, but you could use the same concept as above.