I am trying to change the text of a paragraph tag with a button, and I wanted to test how different styling tags would affect that change. My html looks like this:
<p id="testParagraph"> This <strong> is </strong> a test </p>
<button id="button">Run Test</button>
In my js file, I'm grabbing that tag by its id, and trying to set its inner html like this:
var button = document.getElementById("button");
button.onclick = function() {
document.getElementById("testParagraph").innerHtml = "I changed the inner html, but what do I look like?";
}
I'm not seeing any change when I click the button, and I was wondering if this was caused by something I did incorrectly, or if there's a problem with changing the html like because of the strong tag in the original paragraph tag.
it is innerHTML not innerHtml
var button = document.getElementById("button");
button.onclick = function() {
document.getElementById("testParagraph").innerHTML = "I changed the inner html, but what do I look like?";
}
Demo: http://jsfiddle.net/shseqy0t/
It's .innerHTML, not .innerHtml. Casing is important in JavaScript.
Not much more to say. A simple typo - carry on!
Edit:
Since we have two identical answers though, I thought I'd give an alternative solution to the script.
You can use addEventListener, with a benefit being that you can attach several events to the same element (opposed to a direct onclick). This is not a recommendation, just mentioning that it's an alternative. Use whatever you prefer.
document.getElementById("button").addEventListener('click', function() {
document.getElementById("testParagraph").innerHTML = "I changed the inner html, but what do I look like?";
});
<p id="testParagraph"> This <strong> is </strong> a test </p>
<button id="button">Run Test</button>
Related
So what I'm trying to make is a paragraph in HTML and then when you click on it it would do a certain action, for example:
<p id='hello'>Hello</p>
<script>
hello.onclick = function() {
console.log("clicked!");
}
</script>
the only problem is that when I click next to the text, it still detects it as a click, I want the click ratio to be the length of the paragraph's text. What's the best way I could do this?
I would suggest you to use inline element instead of p like below -
<span id='hello'>Hello</span>
Because p is block element and no matter where your contents gets over in the line it will takes the space of whole line.
For more in details refer this link
I write an example, I think this helps you
you can see the link
<buttom onclick="clickMe()">click me please</buttom>
<div>
<p id="write"></p>
</div>
<script>
function clickMe() {
let getELementP = document.getElementById("write");
getELementP.innerHTML = "writeHere";
}
</script>
I'm working on a project where I have to change the text inside a button, but the button is not allowed to have an ID. I'm wondering how to accomplish this.
If it helps, I am using Kendo UI, which I believe is how the button is given its onClick method using data-bind:
<button class="some-css-classes" data-bind="click: myJavascriptFunction">Text I want to change</button>
You can avoid adding more attributes by just targeting the existing data-bind attribute and change the text inside like this:
var x = document.querySelector('[data-bind="click: myJavascriptFunction"]');
x.innerHTML = "Hello World";
jsFidldle: http://jsfiddle.net/AndrewL64/z7t31psn/1/
Or if you don't want to create an extra variable:
document.querySelector('[data-bind="click: myJavascriptFunction"]').innerHTML = "Hello World";
jsFidldle: http://jsfiddle.net/AndrewL64/z7t31psn/2/
One workaround might be using a data-id attribute.
<button data-id="unique_id">Text I want to change</button>
and then
document.querySelector('[data-id=unique_id]').innerHTML = 'something';
or
$("[data-id=unique_id]").html('something')
if you're using jquery
You can get it by a class
<button class="test">
Test Button
</button>
document.getElementsByClassName('test')[0].innerHTML="Text Changed"
document.getElementsByClassName("class1 class2 class3")[0].innerHTML = "test" replace zero with the appropriate index. This may require updating if the website markup is modified.
I am beginner to coding and js. I have been looking to get started on a little project to change text (i.e. the word "cat") to another piece of text (i.e. dog) on hover? Please help, anything simple to get me started.
I guess what you are trying to achieve raises the following two basic questions:
How do you change the text of an element?
How do you trigger this change when hovering over the element?
To answer your first question you may check out this webpage to find out about basic dom manipulation. You can also have a look at the following code snippet to see how to permanently change a text with "cat" to "dog".
var text = document.getElementById('text')
text.textContent = "dog"
<p id="text">
cat
</p>
To answer your second question you should read about eventlistener. In this case particular you probably want to use the events mouseover and mouseout. The following snippet will provide an example of how to use them:
var text = document.getElementById('text')
text.addEventListener("mouseout", function() {
text.textContent = "cat"
})
text.addEventListener("mouseover", function() {
text.textContent = "dog"
})
<p id="text">
cat
</p>
Since you seem to be a new learner I could also recommend you to read about window.onload since you may be running into some trouble when executing the lines like var text = document.getElementById('text') too early.
Also, you could have a look at the difference between innerHTML and textContent as mentioned by Nick Parsons in a comment. It's actually cleaner to use textContent in this case since we only want to change a text.
This code changes the link text to whatever you have in "data-change", and changes it back again on mouse out.
Cat
<script type="text/javascript">
function changeMe(el) {
newText = el.getAttribute('data-change');
oldText = el.innerText;
el.setAttribute('data-change', oldText);
el.innerText = newText;
}
</script>
Test: https://codepen.io/anon/pen/MzBQod
This is going to be hard to explain but I will do my best. I want to write a Javascript function that takes two parameters (title, content) and creates a <div> tag in the <body> tag. The <div> tag should look like this.
<div>
<h2>title</h2>
<p>content</p>
</div>
My javascript code looks like this:
function addElement (title, content) {
var newDiv = document.createElement("div");
var newH2 = document.createElement("h2");
var title = document.createTextNode(header);
newH2.appendChild(title);
var p = document.createElement("p");
var post = document.createTextNode(entry);
p.appendChild(post);
newDiv.appendChild(newH2);
newDiv.appendChild(p);
// Missing codes here...
}
I dont know how to finish my method. Because of I have almost hundreds of tags inside my page and I want this new tags (when a user makes a new input) will appear on same place somewhere in the middle of the html code page in order to keep things organized.
If you would like to use jQuery take a look at this fiddle: http://jsfiddle.net/panpymq2/
In my fiddle I am binding to a button press. Then I call a method that appends new generated html to the body of the page. You can enter change where you are appending the new HTML with CSS3 selectors. just modify the $("insert selector there").append...
UPDATE
As per the new requirements I have updated my fiddle: http://jsfiddle.net/panpymq2/1/
I now prepend the new html to the document.
You already know how to add elements as children of other elements. That's what you used to add the h2 and p to the div. You could use the same appendChild to add the div to the document:
document.body.appendChild(newDiv);
But you don't want it at the bottom of the page--you want it "in the middle of the html code page". One straightforward way to do this is to add the newDiv to a container that's in the right place, in the middle of the page.
You'd first create this container in the page HTML:
<!doctype html>
<body>
<p>stuff before</p>
<div id="container"></div>
<p>stuff after</p>
</body>
Then, finish off addElement with:
document.getElementById('container').appendChild(newDiv);
One way would be if addElement took a third parameter which is the sibling/parent you want to insert your new element next to/within.
function addElement(title, content, target) {
...
target.insertAdjacentElement('afterend', newDiv);
// or
target.appendChild(newDiv);
}
I think this is as much of an HTML as a CSS problem. I've had the same issue.
One way of solving this problem is to make an (extra) container <div> as follows:
<div id="outer_container_elems">
<div id="inner_container_elems">
...
</div>
</div>
And append to inner_container_elems
Hope this helps!
My first SO question! Here's what I am trying to do:
I'm rewriting a tool that generates some code a user can paste directly into Craigslist and other classified ad posting websites. I have created a list of websites (they populate from a database with PHP) the user can choose from with a radio button, and I want their choice to populate as bare text (not a link) between some <p></p> elements in a textarea. I'm using jQuery for this.
Textarea before the user chooses:
<p id="thing"></p>
Textarea after the user chooses:
<p id="thing">www.somewebsite.com</p>
HTML
<input type="radio" name="sitechoice" value="www.websiteone.com">www.websiteone.com<br />
<input type="radio" name="sitechoice" value="www.secondwebs.com">www.secondwebs.com
<textarea>
Some stuff already in here
Here is the website you chose:
<p id="thing"></p>
More stuff already here.
</textarea>
JS
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val();
alert(website);
$("#thing2").html(website);
});
});
JS Fiddle (With comments)
If you see the JS Fiddle, you can see that I put another p element on the page outside the textarea, and it updates just fine, but the one inside the textarea does not. I have read many other like questions on SO and I'm starting to think that I can't change an element that's between textarea tags, I can only change the entire textarea itself. Please, lead me to enlightenment!
You actually can fairly easily manipulate the text contents of the textarea like it is part of the DOM, by transforming its contents into a jQuery object.
Here is a jsFiddle demonstrating this solution: http://jsfiddle.net/YxtH4/2/
The relevant code, inside the input change event:
// Your normal code
var website = $(this).val();
$("#thing2").html(website);
// This turns the textarea's val into a jQuery object ...
// And inserts it into an empty div that is created
var textareaHtml = $('<div>' + $("#textarea").val() + '</div>');
// Here you can do your normal selectors
textareaHtml.find("#thing").html(website);
// And this sets the textarea's content to the empty div's content
$("#textarea").val(textareaHtml.html());
The empty div wrapping your HTML is so that you can easily retrieve it as a string later using jQuery's .html() method, and so the parse does not fail if additional text is entered around the p element inside the textarea.
The real magic is $($("#textarea").val()), which takes your textarea's text and parses it into an HTML node contained in a jQuery object.
It can't do it the way that you are thinking (i.e., manipulate it as if it were a DOM element), but it is still accessible as the value of the textarea, so you can retrieve it like that, use basic string manipulation to alter it, and then set the updated string as the new value of the textarea again.
Something like this . . . first give the <textarea> an id value:
<textarea id="taTarget">
Some stuff already in here
Here is the website you chose:
<p id="thing"></p>
More stuff already here.
</textarea>
Then alter your script like this:
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val();
var currentTAVal = $("#taTarget").val();
$("#taTarget").val(currentTAVal.replace(/(<p id="thing">)([^<]*)(<\/p>)/, "$1" + website + "$3"));
});
});
Unless you need the <p> element in there, you might consider using a more simple placeholder, since it won't actually act as an HTML element within the textarea. :)
EDIT : Fixed a typo in the .replace() regex.
I know that this answer is a little bit late, but here it goes =)
You can do exactly the way you want to do. But for that, you need to implement a small trick.
by having this HTML
<input type="radio" name="sitechoice" value="www.websiteone.com">www.websiteone.com
<br />
<input type="radio" name="sitechoice" value="www.secondwebs.com">www.secondwebs.com
<p id="thing2"></p>
<textarea id="textarea">
<p id="thing"></p>
</textarea>
you can edit textarea content, as a DOM by implementing something like the function changeInnerText
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val(); // Gets value of input
changeInnerText(website);
//$("#thing").html(website); // Changes
//$("#thing2").html(website); // Does not change
});
var changeInnerText = function(text) {
var v = $("#textarea").val();
var span = $("<span>");
span.html(v);
var obj = span.find("#thing")[0];
$(obj).html(text);
console.log(obj);
console.log(span.html());
$("#textarea").val(span.html());
}
});
As you can see, I just get the information from the textarea, I create a temporary variable span to place textarea's content. and then manipulate it as DOM.
Instead of attempting to insert the text into the <p> element, insert the text into <textarea> element and include the <p> tag. Something like this should do the trick:
Change:
$("#thing").html(website);
to:
$("textarea").html('<p id="thing">'+website+'</p>');
And here is a fiddle: http://jsfiddle.net/nR94s/