Editing a <p> without an id - javascript

I have a element with a child of an empty paragraph. That looks like this. Photo for easier viewing.
<body contenteditable="true" class="cke_editable cke_editable_themed cke_contents_ltr cke_show_borders" spellcheck="true">
<p><br></p>
</body>
How do I edit the area between the two p's using javascript to what ever I want since there is no id on them.
var onlineContent = document.getElementsByClassName("cke_editable cke_editable_themed cke_contents_ltr cke_show_borders");
All I have so far is this.

If you are using Jquery you can try this :
$(".cke_editable p:first").html("The text has changed");
You can also read more about how jQuery :first Selector works here: http://www.w3schools.com/jquery/sel_first.asp

document.getElementsByClassName returns an array-like object so you need to select with:
var onlineContent = document.getElementsByClassName("cke_editable cke_editable_themed cke_contents_ltr cke_show_borders")[0];
var onlineContentInner = onlineContentOuter.getElementsByTagName("p")[0];
the 0-th (meaning first) element.
An alternative method is given with document.querySelector(A_VALID_CSS_SELECTOR) wich return only the first element found (equals document.querySelectorAll(CSS_SELECTOR)[0]).
A valid css selector would be .cke_editable.cke_editable_themed.cke_contents_ltr.cke_show_borders
and your element would be (using document.querySelector):
var onlineContentInner = document.querySelector(".cke_editable p");
There you have it.

It would be like this.
var onlineContent = document.getElementsByTagName("body")[0];
onlineContent.getElementsByTagName("p")[0].innerHTML = "Content between the p tags";
Reference http://www.w3schools.com/jsref/met_element_getelementsbytagname.asp

Related

Inserting div into existing div with class only

I'm trying to create a new div in Javascript with two spans in it, each containing a string of text. They are then meant to be inserted before div.two in div.inner.
The div I'm trying to insert it into only has a class and I cannot target it by any ID, unfortunately.
I have also created a codepen here: https://codepen.io/lisaschumann/pen/BXqJKY
Any help is massively appreciated!
HTML
<html>
<div class="inner">
<div class="one"></div>
<div class="two"></div>
</div>
</html>
JS
window.onload=function(){
var infobox = document.createElement("div");
infobox.classList.add('infobox');
var spanOne = document.createElement("div");
var spanOneText = document.createTextNode('Important text 1');
var spanTwo = document.createElement("div");
var spanTwoText = document.createTextNode('Important text 2');
spanOne.appendChild(spanOneText);
spanTwo.appendChild(spanTwoText);
infobox.appendChild(spanOne);
infobox.appendChild(spanTwo);
var targetDiv = document.getElementsByClassName("inner");
targetDiv.insertBefore(infobox, targetDiv.childNodes[1]);
}
Errors:
Cannot read property '1' of undefined
at window.onload
The main issue is that getElementsByClassName returns a live collection of nodes rather than one node and so you would need to access the correct node in that list similar to an array: targetDiv[0], perhaps.
The easier method is to use querySelector to grab the element you want using its class, for example:
var parent = document.querySelector(".inner");
var two = document.querySelector(".two");
parent.insertBefore(infobox, two);
But! there's even a shortcut method you can use here that allows you to add an HTML string direct to the DOM which might save you a bit of time, and some code.
// Create the HTML
const html = `
<div>
<span>Text alpha</span>
<span>Text beta</span>
</div>`;
// Grab the element containing your "two" class
const two = document.querySelector('.inner .two');
// Using insertAdjacentHTML to add the HTML before the two element
two.insertAdjacentHTML('beforebegin', html);
<div class="inner">Inner
<div class="one">one</div>
<div class="two">two</div>
</div>
insertAdjacentHTML
This doesn't work because of these lines
var targetDiv = document.getElementsByClassName("inner");
targetDiv.insertBefore(infobox, targetDiv.childNodes[1]);
document.getElementsByClassName returns a NodeList. targetDiv.childNodes is undefined, because childNodes doesn't exist on a NodeList.
You need to either use a list operation like Array.prototype.forEach, change getElementsByClassName to getElementByClassName (note the s) or access the first node in the node list using the array indexer syntax.
I assume you meant to do something like this:
var targetDiv = document.getElementByClassName('inner')
targetDiv.insertBefore(infobox, targetDiv.childNodes[1])
This will insert a node in between the first and second child of the first DOM node with the class inner.
Try this out , targetDiv is an array by default due to the getElementsByClassName method , even though it has a single element.Hence you need to specify the index i.e. 0 ( as it's the first element of the array)
var targetDiv = document.getElementsByClassName("inner")[0]; targetDiv.insertBefore(infobox, targetDiv.children[1]); }
Using JQuery
$(document).ready(function(){
$(`<div>Important text 1<span></span>Important text 2<span></span></div>`).insertBefore( ".inner .two" );
)
I would encourage you to use JQuery and then shift to vanilla javascript later on. You can do simple tasks like this in just few lines of code and it is also easily debuggable because of that

How to write to a <div> element using JavaScript?

I've searched around using Google and Stack Overflow, but I haven't seemed to find a answer to this. I want to write text inside a <div> element, using JavaScript, and later clear the <div> element, and write more text into it. I am making a simple text adventure game.
This is what I am trying to do:
<DOCTYPE!HTML>
<body>
<div class="gamebox">
<!-- I want to write in this div element -->
</div>
</body>
As a new user to JavaScript, how would I be able to write inside the div element gamebox? Unfortunately, my JavaScript skills are not very good, and it would be nice if you can patiently explain what happens in the code.
You can use querySelector to get a reference to the first element matching any CSS selector. In your case, a class selector:
var div = document.querySelector(".gamebox");
querySelector works on all modern browsers, including IE8. It returns null if it didn't find any matching element. You can also get a list of all matching elements using querySelectorAll:
var list = document.querySelectorAll(".gamebox");
Then you access the elements in that list using 0-based indexes (list[0], list[1], etc.); the length of the list is available from list.length.
Then you can either assign HTML strings to innerHTML:
div.innerHTML = "This is the text, <strong>markup</strong> works too.";
...or you can use createElement or createTextNode and appendChild / insertBefore:
var child = document.createTextNode("I'm text for the div");
div.appendChild(span); // Put the text node in the div
Those functions are found in the DOM. A lot of them are now covered in the HTML5 specification as well (particularly Section 3).
Select a single element with document.querySelector or a collection with document.querySelectorAll.
And then it depends, on what you want to do:
Writing Text into the div or create an Element and append it to the div.
Like mentioned getElementsByClassName is faster. Important to know it when you use this you get returned an array with elements to reach the elment you want you specify its index line [0], [1]
var gameBox = document.getElementsByClassName('gamebox')[0];
Here how you can do it
//returns array with elements
var gameBox = document.getElementsByClassName('gamebox');
//inner HTML (overwrites fsd) this can be used if you direcly want to write in the div
gameBox[0].innerHTML ='<p>the new test</p>';
//Appending when you want to add extra content
//create new element <p>
var newP = document.createElement('p');
//create a new TextNode
var newText = document.createTextNode("i'm a new text");
//append textNode to the new element
newP.appendChild(newText);
//append to the DOM
gameBox[0].appendChild(newP);
https://developer.mozilla.org/en-US/docs/Web/API/document.createElement
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName

How do I select the anchor of a link wth pure javascript

So if I have a DOM like this :
<div id="foo">
<ul><li></li></ul>
</div>
I understand to grab the div I would do
document.getElementById("foo");
but how could I grab the a ? I am trying to add a class to the a href.
ME = spoiled by jQuery
The only thing that you can select by there is the tag name (a). You can use the getElementsByTagName method for this:
var el = document.getElementsByTagName('a')[0];
el.className = 'foo';
Note that [0] selects the first element found by getElementsByTagName. Obviously this can return multiple elements.
If you want to search just within #foo, you could do this:
var foo = document.getElementById('foo'),
el = foo.getElementsByTagName('a')[0];
This shows that you can use getElementsByTagName to search within the context of another element.
One final method -- that isn't supported in all browsers (i.e. Firefox 3 or before, IE 7 or before) -- is querySelectorAll, which allows you to use CSS selectors much as you would in jQuery. For instance:
var el = document.querySelectorAll('#foo a')[0];

jQuery get content between <div> tags

This'll probably be easy for someone:
var x = '<p>blah</p><div><img src="http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=bsr&FlightID=2997227&Page=&PluID=0&Pos=9088" border=0 width=300 height=250></div>';
How do I extract only the portion between the div tags <div>I want this</div>
Don't focus on the <a> tag as the content could be different inside the div.
This is probably what you need:
$('div').html();
demo
This says get the div and return all the contents inside it. See more here: http://api.jquery.com/html/
If you had many divs on the page and needed to target just one, you could set an id on the div and call it like so
$('#whatever').html();
where whatever is the id
EDIT
Now that you have clarified your question re this being a string, here is a way to do it with vanilla js:
var l = x.length;
var y = x.indexOf('<div>');
var s = x.slice(y,l);
alert(s);
Demo Here
get the length of the string.
find out where the first div occurs
slice the content there.
jQuery has two methods
// First. Get content as HTML
$("#my_div_id").html();
// Second. Get content as text
$("#my_div_id").text();
Give the div a class or id and do something like this:
$("#example").get().innerHTML;
That works at the DOM level.
Use the below where x is the variable which holds the markup in question.
$(x).find("div").html();
use jquery for that:
$("#divId").html()
I suggest that you give an if to the div than:
$("#my_div_id").html();
var x = '<p>blah</p><div><img src="http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=bsr&FlightID=2997227&Page=&PluID=0&Pos=9088" border=0 width=300 height=250></div>';
$(x).children('div').html();
Use the text method [text()] to get text in the div element,
by identifing the element by class or id.
This work for me
var content = '<p> demp text </p>';
$('#wordContent').html(content);
$('#wordContent').html($('#wordContent').text());

How to access HTML element without ID?

For instance in the snippet below - how do I access the h1 element knowing the ID of parent element (header-inner div)?
<div id='header-inner'>
<div class='titlewrapper'>
<h1 class='title'>
Some text I want to change
</h1>
</div>
</div>
Thanks!
function findFirstDescendant(parent, tagname)
{
parent = document.getElementById(parent);
var descendants = parent.getElementsByTagName(tagname);
if ( descendants.length )
return descendants[0];
return null;
}
var header = findFirstDescendant("header-inner", "h1");
Finds the element with the given ID, queries for descendants with a given tag name, returns the first one. You could also loop on descendants to filter by other criteria; if you start heading in that direction, i recommend you check out a pre-built library such as jQuery (will save you a good deal of time writing this stuff, it gets somewhat tricky).
If you were to use jQuery as mentioned by some posters, you can get access to the element very easily like so (though technically this would return a collection of matching elements if there were more than one H1 descendant):
var element = $('#header-inner h1');
Using a library like JQuery makes things like this trivial compared to the normal ways as mentioned in other posts. Then once you have a reference to it in a jQuery object, you have even more functions available to easily manipulate its content and appearance.
If you are sure that there is only one H1 element in your div:
var parent = document.getElementById('header-inner');
var element = parent.GetElementsByTagName('h1')[0];
Going through descendants,as Shog9 showed, is a good way too.
It's been a few years since this question was asked and answered. In modern DOM, you could use querySelector:
document.querySelector('#header-inner h1').textContent = 'Different text';
<div id='header-inner'>
<div class='titlewrapper'>
<h1 class='title'>
Some text I want to change
</h1>
</div>
</div>
The simplest way of doing it with your current markup is:
document.getElementById('header-inner').getElementsByTagName('h1')[0].innerHTML = 'new text';
This assumes your H1 tag is always the first one within the 'header-inner' element.
To get the children nodes, use obj.childNodes, that returns a collection object.
To get the first child, use list[0], that returns a node.
So the complete code should be:
var div = document.getElementById('header-inner');
var divTitleWrapper = div.childNodes[0];
var h1 = divTitleWrapper.childNodes[0];
If you want to iterate over all the children, comparing if they are of class “title”, you can iterate using a for loop and the className attribute.
The code should be:
var h1 = null;
var nodeList = divTitleWrapper.childNodes;
for (i =0;i < nodeList.length;i++){
var node = nodeList[i];
if(node.className == 'title' && node.tagName == 'H1'){
h1 = node;
}
}
Here I get the H1 elements value in a div where the H1 element which has CSS class="myheader":
var nodes = document.getElementById("mydiv")
.getElementsByTagName("H1");
for(i=0;i<nodes.length;i++)
{
if(nodes.item(i).getAttribute("class") == "myheader")
alert(nodes.item(i).innerHTML);
}
Here is the markup:
<div id="mydiv">
<h1 class="myheader">Hello</h1>
</div>
I would also recommend to use jQuery if you need a heavy parsing for your DOM.

Categories

Resources