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 !
Related
My front-end skills are fairly limited. I have a trained language model which generates 'tweets'.
I have this javascript function which currently displays the tweets as a paragraph.
function addResponse(msg) {
document.getElementById("results").textContent = ""
var para = document.createElement("div");
var s = "<div class='center' id='gpt2'> <b> Here what our BOT has to say... </b> </br></br>"
i = 1
for (var key in msg){
var value = msg[key];
console.log(value);
s = s + i + ") " + " <b>" + value + "</b> </br></br>"
i = i + 1
}
para.innerHTML = s + "</div>";
document.getElementById('append').appendChild(para);
}
Instead of displaying in a paragraph, I want to display as a proper tweet.
Here is a tailwind CSS implementation to create the UI of the tweet: https://codepen.io/webcrunchblog/pen/xedQVv
Currently this displays a fixed string "Starhopper". What I want to do is, loop through my array object 'msg' and display all the tweets with the proper UI .
Currently the addResponse() is called as part of ajax callback for successful response. From there how can I include the tailwind CSS code so that I can display every array element in its own tweet UI?
Hope the question is clear.
EDIT: Created this codepen if anyone wants to try it out: https://codepen.io/nikhilno1/pen/RwPBWvb
In the output, there is a tweet and three sentences. I want 3 tweets to be created for each of the sentence.
I've updated a bit of your code here: https://codepen.io/rxna/pen/OJVwMOm
The idea is to:
Clone the tweet element, have added a custom class for that:
var articleNode = document.querySelector(".tweet-body");
var clone = articleNode.cloneNode(true);
Update the text within each element:
var title = clone.querySelector(".tweet-text");
title.innerText = value;
And lastly append within the DOM:
document.getElementById("append").appendChild(clone);
It's not perfect but hopefully you'd get the idea.
I have some code that is roughly along the lines of this:
exportValue = [];
function reduceArray() {
//does something
exportValue = parseFloat(exportValue)
}
From that, I get that exportValue is 73951. I then have to add that number to the page... so I tried both of these:
$("#exportValueDiv").append(exportValue);
$("#exportValueDiv").append("<li>" + exportValue + "</li>");
But that doesn't work.. I'm confused on how to add something like a variable to the DOM....
If I do something like:
$( "#exportValueDiv" ).append( "<li>value</li>")
it works, but I don't want to add a string, I want to add the value of the variable. I looked this up, but I'm still confused, so any help would be greatly appreciated!!!
Look into jQuery manipulation
$("#exportValueDiv").text(exportValue); //Replaces text of #exportValueDiv
$("#exportValueDiv").html('<span>'+exportValue+'</span>'); //Replaces inner html of #exportValueDiv
$("#exportValueDiv").append('<span>'+exportValue+'</span>'); //Adds to the inner html of #exportValueDiv
The .append() contract expects a DOM element or HTML String. You will need to do:
$("#exportValueDiv").append("<div>" + exportValue + "</div>");
Try this:
$("#exportValueDiv").append("<div>" + exportValue + "</div>");
The following appends your variable to a div that already has information:
<div id="exportValueDiv">
<p>
Some information.
</p>
</div>
<script>
var exportValue = "Hello world.";
$("#exportValueDiv").append('<p>'+ exportValue +'</p>');
</script>
https://jsfiddle.net/supadave57/f9tqw0d4/
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
Take the following page with two forms with different classes but each form has an input with the same name.
<form class='first_form'>
<input name='test' value='1' />
</form>
<form class='second_form'>
<input name='test' value='3'/>
</form>
I can get the form index and I know the name of the input but I do not know the index of the input.
Is there a way to chain a selector with the form index and the input name to get the value?
I have tried chaining but nothing seems to work
var inputName = 'test';
Var formIndex = 1;
$('*[name="' + inputName + '"]' +' ' + '$("form").eq(' + formIndex + ')').val();
FIDDLE
var formIndex=0;
var inputName="txtbox";
vall= $("form:eq("+ formIndex+") input[name= "+ inputName +" ]").val();
alert(vall);
your order was wrong
Untested, but could you do:
$('form:nth-of-type(1) input[name="test"]').val();
$("form:nth-child("+formIndex+") input[name='"+inputName+"']").val();
You could do in a more clever way:
var fieldName = 'test';
var formId = '.first_form'
$('form'+formId+' input[name='+fieldName+']).val()
Instead of index, use named selectors, like id or class. It will help you in the future find the correct form (when you will have more than 5, it will be hard to count witch one you are looking at :) )
But that is too complex:)
I would propose something like this:
var currentForm = $('form'+formId);
currentForm//here you can put a log into console if element has not been found and find that bug sooner.
currentForm.find('input[name='+fieldName+']').val()
You can access the form's element directly within the DOM using either of:
document.forms[formIndex]
document.forms[formName]
You can then reference an input element by name using:
document.forms[formIndex][inputName]
document.forms[formName][inputName]
Then just wrap it in $(...) to get yourself a jQuery collection. In your case:
var inputName = 'test',
formIndex = 1;
$(document.forms[formIndex][inputName]);
I imagine this is by far the most performant way, and it's readable too.
To add a little detail, document.forms is an HTMLCollection of all HTMLFormElements within a document. And given any HTMLCollection or HTMLFormElement you can access named elements within them as properties.
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