I have this HTML button:
<button id="myButton" onClick="lock(); toggleText(this.id);">Lock</button>
And this is my toggleText JavaScript function:
function toggleText(button_id)
{
if (document.getElementById('button_id').text == "Lock")
{
document.getElementById('button_id').text = "Unlock";
}
else
{
document.getElementById('button_id').text = "Lock";
}
}
As far as I know, button text (<button id="myButton">Lock</button>) is just like any link text
(Lock). So the fact that it's a button doesn't matter. However, I can't access the button text and change it.
I tried ('button_id'), (button_id), == "Lock", == 'Lock', but nothing works.
How can I access and change a button text (not value) or a link text?
Change .text to .textContent to get/set the text content.
Or since you're dealing with a single text node, use .firstChild.data in the same manner.
Also, let's make sensible use of a variable, and enjoy some code reduction and eliminate redundant DOM selection by caching the result of getElementById.
function toggleText(button_id)
{
var el = document.getElementById(button_id);
if (el.firstChild.data == "Lock")
{
el.firstChild.data = "Unlock";
}
else
{
el.firstChild.data = "Lock";
}
}
Or even more compact like this:
function toggleText(button_id) {
var text = document.getElementById(button_id).firstChild;
text.data = text.data == "Lock" ? "Unlock" : "Lock";
}
document.getElementById(button_id).innerHTML = 'Lock';
You can simply use:
document.getElementById(button_id).innerText = 'Your text here';
If you want to use HTML formatting, use the innerHTML property instead.
Remove Quote. and use innerText instead of text
function toggleText(button_id)
{ //-----\/ 'button_id' - > button_id
if (document.getElementById(button_id).innerText == "Lock")
{
document.getElementById(button_id).innerText = "Unlock";
}
else
{
document.getElementById(button_id).innerText = "Lock";
}
}
Related
I need to ask for some help with this one so here goes...
I'm creating a WYSIWYG editor using a contenteditable textarea. It automatically creates paragraphs and you can also add in subtitles.
What I would like to be able to do is when the button #addStorySubtitle is clicked, if the currently selected p tag is empty or only contains a zero width space , then it will be replaced with the contents of innerDivSubtitle. However, if the p tag has content, use innerDivSubtitle to create a new block level element underneath.
The part I seem to be having trouble with is detecting is the p tag is empty.
Thanks all!
$('#addStorySubtitle').click(function(e){
var innerDivSubtitle = $('<div class="addStorySubtitleWrap" contenteditable="false"><span class="removeStorySubtitle"></span><textarea name="addstorysubtitle" class="addStorySubtitle autoSize" placeholder="Really good subtitle" contenteditable="true"></textarea></div><p><p>');
var sel = window.getSelection();
if ($(sel.anchorNode.parentNode) === "") {
alert('empty'); //just for help
$(sel.anchorNode.parentNode).replaceWith(innerDivSubtitle);
} else {
alert('not empty'); //just for help
$(sel.anchorNode.parentNode).after(innerDivSubtitle);
}
});
UPDATE
Thanks for all of your helpful replies!
It turns out that the zero width space detection was causing the issue and I had to use unicode to detect it. Here's what I did to fix it...
var nodCon = $(sel.anchorNode.parentNode).html();
if (nodCon === "" || nodCon === "\u200b"){
alert('empty');
}
I hope this will help you?
if($('p').html() == "" || $('p').html == ""){
//Do something
}
You can check whether the element has content like this:
checkElementContents(document.getElementById('p1'));
checkElementContents(document.getElementById('p2'));
function checkElementContents(element) {
if (element.innerHTML) {
console.log(element.id + " is not empty");
} else {
console.log(element.id + " is empty");
}
};
<p id="p1"></p>
<p id="p2"> </p>
Be careful with spaces, carriage return etc...
function isEmpty(ele)
{
var count = ele.html().replace(/\s*/, '');
if(count>0)
return false;
return true;
}
console.log(isEmpty($('p')));
Check if empty the following way:
if ($("Your p tag").val().length == 0) { /* Empty */ }
I want to overwrite some standard text from my CMS.
<form accept-charset="UTF-8" action="/da-DK/listings" class="new_listing"
enctype="multipart/form-data" id="new_listing" method="post"
novalidate="novalidate"><div style="margin:0;padding:0;display:inline">
<input name="utf8" type="hidden" value="✓"><input name="authenticity_token" type="hidden"
value="vvEeH5tHhuGME4jNDPhw0o4w8KoWpwgchgrU7xG/7LQ="></div>
<label class="input" for="listing_title">CHANGE THIS TEXT</label>
I want to change the text where it says "CHANGE THIS TEXT" using javascript. I know very basic javascript though, so I hoped someone here could help me.
I already have code that enables me to change a text with an ID, but this label doesn't have an ID, so I don't know how to go about it.
Thank you for your time.
The script can only be posted in the head section of the whole site (even though it's specific to one ingle page).
Here is my other script that worked for ID:
<script>
var texts = [];
texts["new-listing-link"] = "NEW TEXT HERE";
var interval = setInterval(function() { setText(); }, 100);
function setText() {
var textsCopy = texts.slice();
for (var key in texts) {
var element = document.getElementById(key);
if (element != null) {
element.innerHTML = texts[key];
delete texts[key];
}
}
if (texts.length == 0) {
window.clearInterval(interval);
}
}
</script>
How can I go about it? :)
I'm pretty sure I'm only allowed to use javascript and not jQuery
Here's another way, no need to change what you've got
document.querySelector('label[for=listing_title]').innerHTML = 'New Label';
no jQuery bloat, no fumbling through arrays, quick and simple
querySelector works just like jQuery, but it has native speed and zero bloatage.
label[for=listing_title] finds the label that has an attribute "for" with the value "listing_title" ... so, while not guaranteed to be unique, not many forms have more than one label "for" an input
var texts = {}; // note {} not []
texts["label[for=listing_title]"] = "NEW TEXT";
var interval = setInterval(function() {
setText();
}, 100);
function setText() {
var textsCopy = texts.slice(); // why???
for (var key in texts) {
var element = document.querySelector(key);
if (element != null) {
element.innerHTML = texts[key];
delete texts[key];
}
}
if (texts.length == 0) {
window.clearInterval(interval);
}
}
With the above version, you can mix id's as well as the more complex selectors ... so, your original substitution could be done as well in the same loop by adding
texts["#new-listing-link"] = "NEW TEXT HERE";
Note the '#' before the id
Another hint or two:
var texts = {
"label[for=listing_title]": "NEW TEXT",
"#new-listing-link": "NEW TEXT HERE"
}; // declare the text object in one go
var interval = setInterval(setText, 100); // this is equivalent (not exactly identical, but functionally identical to your code
// rest of your code
The script can only be posted in the head section of the whole site (even though it's specific to one ingle page).
Here is my other script that worked for ID:
<script>
var texts = [];
texts["new-listing-link"] = "NEW TEXT HERE";
var interval = setInterval(function() { setText(); }, 100);
function setText() {
var textsCopy = texts.slice();
for (var key in texts) {
var element = document.getElementById(key);
if (element != null) {
element.innerHTML = texts[key];
delete texts[key];
}
}
if (texts.length == 0) {
window.clearInterval(interval);
}
}
</script>
How can I go about it? :)
I'm pretty sure I'm only allowed to use javascript and not jQuery
This should do the trick (quick'n'dirty):
slice=Function.prototype.call.bind([].slice);
slice(document.querySelectorAll(".input")).map(function(x){ return x.textContent="Killroy was here"; });
Check the Fiddle
MDN on Array.prototype.slice()
MDN on Array.prototype.map()
MDN on Document.querySelectorAll()
If you need just this label, choose:label[for=listing_title] as in Jaromanda Xs answer
var label = document.getElementsByTagName("label")[0] // If this is the first label of the page
label.value = "new text";
I need a Simple script that searches a HTML for a certain code so its not displayed.
My current code only replaces the whole text. But if a person changes 1 item, it can't find it.
Is there a way to make a Wild Card, to find text like:
Thesite
...and if it finds something with
<*yourdomain*</a>
then it replaces the whole <a href....>..</a> with Blank?
My current code is :
function checkLoad(){
if (document.readyState === "complete") {
document.body.innerHTML = document.body.innerHTML.replace(
'<p style="text-align:center;">My Website is redriv</p>',
""
);
} else {
setTimeout('checkLoad();', 500)
}
}
If you want to base this just on the href, you can do it with a CSS rule:
a[href=http://www.yourdomain.com] { display: none; }
To find any href containing 'yourdomain', then use *=:
a[href*=yourdomain] { display: none; }
If you want to include a check of the anchor text as well, you need JS:
function array(a) { return Array.prototype.slice.call(a); }
function check(a) { return /yourdomain/.test(a.textContent); }
function hide (a) { a.style.display = 'none'; }
var selector = 'a[href*=yourdomain]';
var anchors = array(document.getQuerySelector(selector));
anchors . filter(check) . forEach(hide);
No, don't use regexp for this or any other HTML manipulation.
RegEx would be the easiest solution here, something like <a.*yourdomain.*?\/a> should do the trick. It will remove anchor tags that contain yourdomain inside them (both as attributes and attribute values - you didn't specify how accurate you want it, so everything gets triggered). See it here:
var html = 'ThesiteGood URLGood URL';
var replaced = html.replace(/<a.*yourdomain.*?\/a>/, '');
document.getElementById('f').textContent = html;
document.getElementById('r').textContent = replaced;
p {color: #777}
span {color: black}
<p>Sample markup: <span id="f"></span></p>
<p>After RegEx: <span id="r"></span></p>
Used one-line sample markup on purpose so you can see it won't touch the other anchors.
So your full code would be:
function checkLoad(){
if (document.readyState === "complete") {
document.body.innerHTML = document.body.innerHTML.replace(/<a.*yourdomain.*?\/a>/, '');
} else {
setTimeout('checkLoad();', 500)
}
}
I must be daft, but the javascript is not changing the containing div text as I would expect once the div is clicked:
favourite.onclick = function() {
loadXMLDoc('indexFavourite');
var linkclass = favourite.className;
if(linkclass == 'favouriteOption')
favourite.className = 'favouriteOptionActive',
favourite.className.update("New text");
else
favourite.className = 'favouriteOption';
}
Your syntax is way off, missing bracket and whatnot
favourite.onclick = function() {
loadXMLDoc('indexFavourite');
var linkclass = favourite.className;
if(linkclass == 'favouriteOption') {
favourite.className = 'favouriteOptionActive',
favourite.innerHTML="New text";
}
else {
favourite.className = 'favouriteOption';
}
}
What you are doing here is changing the class of a div (probably). And even this is kinda wrong. I mean
favourite.className = 'favouriteOptionActive',
favourite.className.update("New text");
should actually produce an error, because the string favouriteOptionActive doesn't have a method update. It could have only if you patch the String.prototype.
If you want to change the div's text you should use div.innerHTML or div.innerText.
favorite.text('New text') will set the text
note this will work if using jQuery, my bad!
I see examples for this all over, but for some reason, mine isn't working. I have a textbox that is added dynamically if a certain value is selected in a select list.
The part where the field shows up is working, but I am also trying to add some text to the box, which I can't get to work. I'm also trying to use JS to select the text once it's entered - but haven't gotten that far yet!
Is there something blatantly wrong with this?
function showBox() {
if (document.getElementById("ctl00_Content_WhereFound").value == "Other" || document.getElementById("ctl00_Content_WhereFound").value == "Friend/Employee Referral")
{
document.getElementById('ctl00_Content_WhereDetails').style.display = "inline";
if (document.getElementById("ctl00_Content_WhereFound").value == "Other") {
document.getElementById('ctl00_Content_WhereDetails').innerHTML += 'Enter Other';
} else {
document.getElementById('ctl00_Content_WhereDetails').innerText += "Enter Referral";
}
}
}
First thing I noticed was that you used 'innerHTML' in your if clause and 'innerText' in your else clause. Was that on purpose? They do different things...
It's a pain, but it might be worth using the document.createElement() etc functions to build/modify the dynamic content.
I've had trouble with similar stuff... in general, using the DOM functions rather than innerHTML often fixes it, though it is significantly more verbose. JQuery has some very helpful functions for this.
try this..
function showBox()
{
$Found = document.getElementById("ctl00_Content_WhereFound");
$Where = document.getElementById('ctl00_Content_WhereDetails');
if($Found.value == "Other" || $Found.value == "Friend/Employee Referral")
{
$Where.style.display = "inline";
if($Where.value == "Other")
{
$Where.value = 'Enter Other';
}else
{
$Where.value = "Enter Referral";
}
}
}
You can always assign elements to variables to shorten your code.
This looks like you're attempting to make a change to Asp.Net rendered controls. Make sure you have the actual id of the controls formatted correctly. Typically the UniqueID is formatted like ctl00_Content_WhereFound but the ClientID is formatted ctl00$Content$WhereFound.
innerText isn't supported by at least Firefox. Is there a reason you can't use innerHTML in both cases?
Also, you might want to store the element references to make your code cleaner and faster:
function showBox() {
var eFound = document.getElementById("ctl00_Content_WhereFound");
if (eFound.value == "Other" || eFound.value == "Friend/Employee Referral")
{
var eDetails = document.getElementById('ctl00_Content_WhereDetails');
eDetails.style.display = "inline";
if (eFound.value == "Other") {
eDetails.innerHTML += 'Enter Other';
} else {
eDetails.innerHTML += "Enter Referral";
}
}
}