Add div below particular div using Javascript - javascript

I have some class name fawas that displays some content. Actually i have to add some content below the Div in java script.please help me.
<div class="fawas">
this is my name fawas khan.
</div>
my javascript code is
var dynamic = "this is my contact number.";
var _body = document.getElementsByTagName('body') [0].innerHTML
=dynamic;
what i'm getting is only a appended div.

In pure javaScript, getting an element by className is ugly. See How to Get Element By Class in JavaScript? for more information.
Basically, you'll want this function:
function getElementsByClass(tagType, className) {
var elems = document.getElementsByTagName(tagType);
var returns = [];
for (var i in elems) {
if ((' ' + elems[i].className + ' ').indexOf(' ' + className + ' ') > -1) {
returns.push(elems[i]);
}
}
return returns;
}
Once you have that, the rest is not too bad:
var dynamic = document.createElement("div");
dynamic.innerHTML = "this is my contact number.";
var elements = getElementsByClass("div", "fawas");
if (elements.length > 0) {
// just change the first, as you did in your post
elements[0].parentNode.insertBefore(dynamic, elements[0].nextSibling);
}
I dynamically create your new div, rather than just a text string.
Then, I get the parent of the element you want to insert after, use the insertBefore function on whatever is after the element of your choice.
Here is a working fiddle.
As others have shown you, this can be a lot cleaner using jQuery. I don't know enough node.js to know if it has functions that will be more convenient, so I gave a pure JS solution.

In case you're interested in jQuery solution, here's a Fiddle
<div class="fawas">
this is my name fawas khan.
</div>
$(function(){
var dynamic = ('this is my contact number.');
$('.fawas').after('<div class="fawas2">'+dynamic+'</div>');
});

Your html should be,
<div class="fawas">
this is my name fawas khan.
</div>
<div id="fawas-2">
</div>
Your script should be,
<script type="text/javascript">
var dynamic = "this is my contact number.";
document.getElementById('fawas-2').innerHTML =dynamic;
</script>

You can do this
var oldcontent = document.getElementsByTagName('body') [0].innerHTML;
document.getElementsByTagName('body') [0].innerHTML = oldcontent + dynamic
Where dynamic is the content you want to add

Related

Problems with adding links to an itens in Javascript

I need to add links to some divs in Wordpress, so I tried writting some JS code for it. But I keep getting the following error " Uncaught TypeError: addId.setAttribute is not a function "
I'll leave the code down bellow. Thank you everyone for the help
var addId = document.getElementsByClassName("elementor-repeater-item-d7362c2");
addId.setAttribute('id', "item");
ogElement = document.getElementByid("item").innerHTML;
addLink = "<a href='https://www.vivendus.com.br/product-category/colar/'>" + ogElement + "</a>";
document.getElementByid("test").innerHTML = addLink;
.elementor-repeater-item-d7362c2 {
color:#ccff00;
font-size:2em;
}
<div class ='elementor-repeater-item-d7362c2'> test <div>
document.getElementsByClassName returns a collection of elements, not an element. You should specify which element you are working with.
var addId = document.getElementsByClassName("elementor-repeater-item-d7362c2");
This will return an array or a list if i remember right, you need to get it by id or iterate on addId and setAttribute on each element !

Javascript: Add HTML to string - make a link and add it to output

New to javascript, how do I fix this problem I'm having?
I want to add an a tag to a string variable that i'm creating using a function.
The whole message (eg - "Your tutor is JOHN DOE. Contact them here: CONTACT FORM") Is added to the DOM with another function (which works).
When I run the script it outputs to the browser but the second part (makeLink()) doesnt work.
This is what I get: "Your tutor is JOHN DOE. Contact them here http://www.example.com" - Instead of the URL I want word CONTACT FORM which should be a link.
How do I do this?
I tried using link() Method, which also didnt work and had similar output.
I'll only include the relevant script below, the rest works fine...
function makeMessage(){
for(i in msgArr){
stringMSG += msgArr[i];
//do not add a comma after last item
if(i < msgArr.length - 1){
stringMSG += ', ';
}
}
var highRiskmsg = "Your tutor is " + stringMSG + ". Contact them here" + makeLink();
return highRiskmsg;
}
function makeLink() {
var contactLink = document.createElement("a");//create <a> tag
contactLink.setAttribute("id", "linkC");//set id att for <a> tag
contactLink.setAttribute("href", "http://www.example.com/contact.php");//set id att for <a> tag
var contactLinkTxt = document.createTextNode("CONTACT FORM");//new text node
contactLink.appendChild(contactLinkTxt);//append text as child of <a> tag
return contactLink;
}
It seems the problem is you are returning a DOM element from your makeLink() function, and this won't concat with the string as you expect.
You need to return a valid HTML string instead, such as: <a id=".." href="..">..</a>
The quickest way to fix your code would be just to change the return for the makeLink() function as follows:
return contactLink.outerHTML;
Using outerHTML will return the HTML string for the element, rather than the element itself.
Here is a working example
As an alternative to musefan's answer, you can return an element that contains both the message and link as nodes, instead of text.
function makeMessage(){
var highRiskmsg = "Your tutor is " + msgArr.join(',') + ". Contact them here";
var span = document.createElement('span');
span.appendChild(document.createTextNode(highRiskmsg));
span.appendChild(makeLink());
return span;
}
Fiddle

Having difficulty building a form summary with JS

Sorry for the noobish question but, I am trying to build a form summary that will populate a div (immediately) with all of the fields being used. Here is a small sample of the field: Fiddle
For some reason the JS is not working as I would expect it to, can anyone point out what I am doing wrong?
For example, I would like it to output: "AND name: john EXCEPT number 222".
I would also like to be able click on a result to remove it, and clear the field. Thank you
$(".allS").change(function () {
if ($(this).next('.textArea').not(':empty'))
// varible to hold string
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("#text_here").text(str);
}).change();
$('.textArea').change(function(){
var $inputs = $('form#form :input[type="text"]'),
result = "";
$inputs.each(function(){
// access the individual input as jQuery object via $(this)
result += $(this).val()+"<br>";
});
// store result in some div
$('div#text_here').text(result);
}).change();
There were many mistakes in your code. I simplified it to a very short code that only does what's needed to get the output you requested. Here's the working fiddle.
$(".allS, .textArea").change(function () {
var str = '';
if ($('#name').val().length > 0 && $('#number').val().length > 0)
var str = $('#nameMod>option:selected').text() + ' name:' + $('#name').val() + ' ' + $('#numberMod>option:selected').text() + ' number ' + $('#number').val();
$("#text_here").html(str);
});
Basically, what this does is attach a change event handler to both classes (.alls, .textArea), and when the event is triggered, both input fields are tested for any content. If this test passes, a string is composed out of all the relevant values, and the div content is set. If the test failed (no content), the str variable contains an empty string and the div is cleared.
Just glancing at the code, the selector 'form#form :input[type="text"]' looks wrong. For starters, input is not a pseudoclass. Also, attribute matching shouldn't have the quotes.
This may or may not be what you want (I think it is, from looking at your html):
'form#form input[type=text]'
Also your <br>'s are not working because you called text(). call html() instead.

JQuery: Selecting elements with unique class AND id

I have this html code:
<div class="category" id="154"> Category </div>
<div class="category2" id="156"> Category2 </div>
<div class="category3" id="157"> Category3 </div>
<div class="category4" id="158"> Category4 </div>
<input type="text" />
So in example if I write a id in text box, how to select div .category with this ID and get inner HTML text. With jQuery
so you only need to use the ID as this is a unique value (or should be)
var html = $("#154").html();
NOTE: If you do have duplicate ID values in use then it is important to note that JQuery will only select the first one.
if you want to do this when a textbox value is entered you could do this on the textbox change event...
$("input").change(function(){
var id = $(this).val();
var element = $("#" + id);
if(element){
var html = element.html();
//do something with html here
}
});
NOTE: you may want to put an ID value on your textbox to ensure you get the correct control
Although I strongly suggest you find a way around using duplicate ID values, you could have a function like this to get the DIV you want...
function GetContent(className, id) {
var result = null;
var matchingDivs = $("." + className);
matchingDivs.each(function(index) {
var div = $(matchingDivs[index]);
if (div.attr("id") == id) {
result = div.html();
}
});
return result;
}
Click here for working example
I recommend you give the textbox an ID, in case you add other textboxes to the page.
But if you only have the 1 text input, the following would work:
var id = $('input:text:first').val();
var innerHtml = $('#' + id).html();
Here is a jsFiddle that will alert the html using this technique whenever the text in the textbox changes.
$("#id.class")
will select the necessary element by both class and ID (replacing id and class with their respective names, of course).
Adding .html() to the end will get you the content.
i.e:
$("#id.class").html()

Match a String in a Webpage along with HTML tags

With below code, I am trying to match a text in a web page to get rid of html tags in a page.
var body = $(body);
var str = "Search me in a Web page";
body.find('*').filter(function()
{
$(this).text().indexOf(str) > -1;
}).addClass('FoundIn');
$('.FoundIn').text() = $('.FoundIn').text().replace(str,"<span class='redT'>"+str+"</span>");
But it does not seems to work.. Please have a look at this and let me know where the problem is...
here is the fiddle
I have tried the below code instead..
function searchText()
{
var rep = body.text();
alert(rep);
var temp = "<font style='color:blue; background-color:yellow;'>";
temp = temp + str;
temp = temp + "</font>";
var rep1 = rep.replace(str,temp);
body.html(rep1);
}
But that is totally removing html tags from body...
change last line of your code to below one...you are using assignment operator which works with variables not with jquery object ..So you need to pass the replaced html to text method.
$('.FoundIn').text($('.FoundIn').text().replace(str,"<span class='redT'>"+str+"</span>"))
try this.
$('*:contains("Search me in a Web page")').text("<span class='redT'>Search me in a Web page</span>");

Categories

Resources