How to append an element before another using Javascript? - javascript

I tried following the a wiki and looking into multiple questions here but I still have problems with insertBefore..
This is my sample:
<div id="container">
<span id="first">1</span>
<span id="second">2</span>
<div id="third">3</div>
<div id="forth">4</div>
</div>
<script>
topbar = document.getElementsById("container");
boardlist = document.getElementsById("first");
bmcontainer = document.createElement("span");
bmcontainer.setAttribute("id", "zero");
bmcontainer.innerHTML("0");
topbar.inserBefore(bmcontainer, boardlist);
</script>
I want to append the span#zero before the span#first. What am I doing wrong? I'm trying to not use jQuery, so I'm looking for a totally javascript solution.

Node.insertBefore() is the answer.
var insertedNode = parentNode.insertBefore(newNode, referenceNode);
If you have Parent Node, then you should use ParentNode.prepend()
ParentNode.prepend(nodesToPrepend);
Take a look # mentioned links for full documentation and examples.
Update
You have some issues in your code (typo and wrong usage of innerHTML), here is fixed code.
HTML
<div id="container">
<span id="first">1</span>
<span id="second">2</span>
<div id="third">3</div>
<div id="forth">4</div>
</div>
JS
var topbar = document.getElementById("container"),
boardlist = document.getElementById("first"),
bmcontainer = document.createElement("span");
bmcontainer.setAttribute("id", "zero");
bmcontainer.innerHTML = "0"; // innerHTML is not a function, it's a property
topbar.insertBefore(bmcontainer, boardlist);
jsfiddle
Notice that InnerHTML is not a function, it's a property, read more about that here: Element.innerHTML

Prepend pure javascript
MDN article on insertBefore()
var el = document.getElementById('thingy'),
elChild = document.createElement('div');
elChild.innerHTML = 'Content';
// Prepend it
el.insertBefore(elChild, el.firstChild);
Source: http://clubmate.fi/append-and-prepend-elements-with-pure-javascript/#Prepend
Also, the jQuery prepend() Method
You can read about it here and here.

You can use the insertAdjacentElement function.
var boardlist = document.getElementById("first"),
bmcontainer = document.createElement("span");
bmcontainer.setAttribute("id", "zero");
boardlist.insertAdjacentElement('beforebegin', bmcontainer);
Element.insertAdjacentElement

Related

Using regex with javascript on nodejs find html attribute and prepend something to its value

I have some markup in JS as follows:
<div class="col-sm-4">
<span id="some-media" class="media">Text</span>
</div>
I would like to select the class attribute of the span and prepend its value with lets say the characters: "::". So after the regex replace i would end up with:
<div class="col-sm-4">
<span id="some-media" class="::media">Text</span>
</div>
EDIT: Note that the order of the attributes in the HTML element is variable so my span attributes could very well have different order like so:
<div class="col-sm-4">
<span class="::media" id="some-media" >Text</span>
</div>
You got a regex solution, this is a DOMmy one:
var html = `<div class="col-sm-4">
<span id="some-media" class="media">Text</span>
</div>`
var doc = (new DOMParser()).parseFromString(html, "text/html");
var el = doc.getElementsByTagName('span')[0];
el.setAttribute('class', '::' + el.className);
console.log(
doc.getElementsByClassName('::media').length > 0 // check if modification's done
);
Since you have no way except Regular Expressions this can be considered as a workaround:
(<span[^>]*class=.)([^'"]+)
JS:
var html = `<div class="col-sm-4">
<span id="some-media" class="media">Text</span>
</div>
<span class="media" id="some-media">Text</span>
`;
console.log(
html.replace(/(<span[^>]*class=.)([^'"]+)/g, `$1::$2`)
);
This isn't using regex, but you can do it like this in vanilla JavaScript:
const el = document.getElementsByClassName('media')[0];
el.className = '::' + el.className;
Or in jQuery:
const $el = $('div span.media');
$el.attr('class', '::' + $el.attr('class'));
Hope this helps.
Don't parse html with regex, use DocumentFragment (or DOMParser) object instead:
var html_str = '<div class="col-sm-4"><span class="media">Text</span></div>',
df = document.createRange().createContextualFragment(html_str),
span = df.querySelector('span');
span.setAttribute('class', '::' + span.getAttribute('class'));
console.log(df.querySelector('div').outerHTML);
I think this is what you're after:
var test = $("#some-media")[0].outerHTML();
var test2 = '<div id="some-media" class="media">Text</div>'
if(/span/.test(test)) //Valid as contains 'span'
alert(test.replace(/(class=")/g, "$1::"));
if(/span/.test(test2)) //Not valid
alert(test.replace(/(class=")/g, "$1::"));
Since the order differs, writing a regex that captures all possible combinations of syntax might be rather difficult.
So we'd need a full list of rules the span follows so we can identify that span?
Got some more info about if the span occurs in a longer HTML string? Or is the string this span and this span only?
An alternative would be to use one of the several node DOM modules available, so you can work with HTML nodes and be able to use any of the above solutions to make the problem simpler.
But since you're using node:
1) Are you using any templating engines? If so, why not rerender the entire template?
2) Why does the class name have to change on the server side? Isn't there a workaround on the clientside where you do have access to the DOM natively? Or if it's just to add styling, why not add another css file that overwrites the styling of spans with className 'media'?
3) If all of the above is not applicable and it;s a trivial problem like you say, what error di you get using a simple replace?
strHTML.replace( 'class="media"', 'class="::media"' )
or if it has to be regex:
strHTML.replace( /class=\"(.*)\"/, 'class=\"::$1\"' );

How to detect element with DOM JavaScript?

I want to detect an element and change the backgroundColor through JavaScript but am having trouble with it.
I can't check for the element because it is a tag+class + tag+class...
Here's my code :
var one = document.getElementsByTagName("div");
var two = document.getElementsByClassName("red");
var three = document.getElementsByTagName("h2");
var four = document.getElementsByClassName("title");
one.two three.four.style.backgroundColor ="#00c497";
The format is "div.red h2.title".
How can I correctly detect an element using DOM JavaScript?
If you can, use querySelector for this:
document.querySelector("div.red h2.title").style.backgroundColor = "#00c497";
<div>
<h2>Don't Touch</h2>
</div>
<div class="red">
<h2>Don't Touch</h2>
<h2 class="title">Change</h2>
</div>

Unable to Append Child in JavaScript using appendChild

I am trying to append some html which is coming as a string in a div but some how appendChild is not working as expected here is my JS code:
var doc = document.getElementById("products");
var notes = doc.getElementsByClassName("product_grid");
var str = '<div>New Node 3<div><div>New Node 4<div>';
var child = document.createElement('div');
child.innerHTML = str;
child = child.firstChild;
notes.appendChild(child);
Here is my HTML:
<div id="products" >
<div class="product_grid">
<div>
Existing node 1
<div>
<div>
Existing node 2
<div>
</div>
</div>
What is wrong with it its unable to Identify the appendChild as a function and keeps giving me error TypeError: notes.appendChild is not a function here is working fiddle
notes is a NodeList. So you'll have to use index to select the elements.
Try this:
notes[0].appendChild(child); // Appends to first product_grid

Get content from id inside id?

I have HTML like:
<div id='content'>
<div id='price'>$100</div>
<div id='another'>something</div>
</div>
I can get content from id="content" like.
vl = document.getElementById("content").value;
In this id, I have another id="price". But I cannot get directly content from id="price".
How can I get content from id="price" through id='content'.Thank you.
jQuery:
$("#price").text();
javascript:
document.getElementById("price").innerHTML;
DEMO
You can use as below :
vl = document.getElementById("price").innerHTML;
JSFiddle - Check it out
YOu can also use jquery using .html() or .text() method
Try,
$('#content').html().find('#price').html();
Try this,
var parent = document.getElementById('content');
var childNodes = parent.childNodes;
for(var i = 0, len = childNodes.length;i<len;i++){
if(childNodes[i].id === "price") {
alert(childNodes[i].innerHTML);
}
}
Using jquery,
$("#content > #price").text();
You can get value of price directly as :
v2 = document.getElementById("price").value;
using Jquery,
v1= $('#content').html();
v2=v1.find('#price');
v3=v1.find('#another')
Try this out:- http://jsfiddle.net/adiioo7/C3C4x/1/
var price = document.querySelector("#content #price").innerHTML;
console.log(price);
IDs should only be used when there is one of that item on the page. You will have no other chance as to re-assign your IDs, or alternatively using the class attribute.
Try this way to select,
var vl = document.getElementById("content").getElementsByClassName("price")[0];
HTML
<div id='content'>
<div class='price'>$100</div>
<div class='another'>something</div>
</div>
You need to access the child element through parent element... that is your question right.. i solve it with jquery DEMO
$(document).ready(function(){
var tem = $('#content').children('#price').text();
alert(tem);
});

javascript to replace all instances of a text within [] with hyperlinks

Am now facing an other challenge. Some parts of my html code has the following lines:
<div class="action-body flooded"><p>(In <span class="error">[82681]</span>) refs AGLBD-16096<br/></div>
I have to get the number with-in the [] and then replace it with a hyperlink. I have tried using document.getElementsByClassName('error') but its not working. how can I make it work? and i would also need to iterate in a loop to replace all such numbers if there are more than one in []. e.g: [123] [234] [345]...
This is all what I have written till now with pimvdb's help:
<script type="text/javascript">
var bodyText = document.getElementById('body').innerHTML;
var pattern = /\[.*?\]/g;
var replaceText = "Pradeep";
document.getElementById('body').innerHTML = bodyText.replace(pattern, replaceText);
</script>
This JSFiddle does what you need: http://jsfiddle.net/TNyms/
When you replace getElementById('body') with document.body, the code works for me.
var body = document.body;
var link = "Pradeep";
body.innerHTML = body.innerHTML.replace(/\[.*?\]/g, link);
That replaces all IDs in this with links:
<div class="action-body flooded">
<p>(In
<span class="error">[82681]</span>) refs
AGLBD-16096
<br/>
</div>
<div>[123][abcd]</div>
<div>[456]</div>
<div>[789]</div>
Outputs:
(In Pradeep) refs AGLBD-16096
PradeepPradeep
Pradeep
Pradeep
Try it with this fiddle.
Your question appears to be related to what is asked in the below link. You may refer this
Replace number in a string using regex or something else

Categories

Resources