Hi is there a way to make the appended "YAY" be of a different style from the "I am happy" text? eg. bigger font-size/ bolded.
document.getElementById("appendButton").onclick = function() {
document.getElementById("happy").innerHTML += " YAY";
}
<p id="happy">I am happy</p>
<button id="appendButton">Click here to cheer!</button>
I've tried to give it an id with span, but then the button won't append anything. Would appreciate any help thanks!
You won't be able to use an id because ids must be unique (which means you can't have more than one on a page and expect the correct output).
Add a class instead.
Note 1: I've used the more modern addEventListener method here.
Note 2: It's also worth mentioning that concatenating HTML strings to innerHTML is considered bad practice. insertAdjacentHTML is the better alternative.
const button = document.getElementById('appendButton');
const happy = document.getElementById('happy');
button.addEventListener('click', handleClick, false);
function handleClick() {
happy.innerHTML += '<span class="yay"> YAY</span>';
}
.yay { color: blue; font-weight: 600; }
<p id="happy">I am happy</p>
<button id="appendButton">Click here to cheer!</button>
You can append a span element with a class, then style it with CSS:
document.getElementById("appendButton").onclick = function() {
document.getElementById("happy").innerHTML += "<span class='large'>YAY</span>";
}
.large{
font-size:20px;
font-weight:bold;
}
<p id="happy">I am happy</p>
<button id="appendButton">Click here to cheer!</button>
Related
I want to insert some unknown HTML (contentToInsert) and remove it later at some point.
If I use insertAdjacentHTML, I cannot later say
myDiv.insertAdjacentHTML('afterbegin', contentToInsert);
myDiv.querySelector('contentToInsert') //cannot work of course
because this does not have id or classname.
I cannot wrap it like this (so I have reference to it later):
var content = document.createElement('div');
content.classList.add('my-content-wrap')
content.innerHTML = contentToInsert;
myDiv.insertAdjacentHTML('afterbegin', adContent);//it can be any allowed position, not just afterbegin
Basically I want to remove it later at some point but dont know how to select it. I dont know the position in which this is going to be instered.
Since insertAdjacentHTML only accepts a string you can
Define your content as a string
Use a template/string to add it
Add that string to myDiv.
Then you can target myDiv again with a selector pointed at that element with the my-content-wrap class, and remove it from the DOM.
const myDiv = document.querySelector('#myDiv');
const content = 'Disappears after two seconds';
const html = `<div class="my-content-wrap">${content}</div>`;
myDiv.insertAdjacentHTML('afterbegin', html);
const pickup = myDiv.querySelector('.my-content-wrap');
setTimeout(() => pickup.remove(), 2000);
<div id="myDiv">Original content</div>
You said "I want to insert some unknown HTML (contentToInsert) and remove it later at some point"
I wouldn't use insertAdjacentHTML at all. Here's how you can achieve it:
let myDiv = document.getElementById('myDiv');
let contentToInsert = "<h1>Some html content</h1>";
myDiv.innerHTML = contentToInsert;
This will insert your content into your div. And you can remove it with:
myDiv.innerHTML = "";
in one of the cases...
const
divElm = document.querySelector('#div-elm')
, Insert_1 = '<span>inserted content 1 </span>'
, Insert_2 = '<span>inserted content 2 </span>'
;
divElm.insertAdjacentHTML('afterbegin', Insert_1);
const ref_1 = divElm.firstChild;
divElm.insertAdjacentHTML('afterbegin', Insert_2);
const ref_2 = divElm.firstChild;
ref_1.classList.add('RED')
ref_2.classList.add('BLU')
console.log( '', ref_1, `\n`, ref_2 )
.RED { color: red; }
.BLU { color: blue; }
<div id="div-elm">
blah blah bla..
</div>
many amazing people already answered your question but here's a workaround, if you're only Adding this specific html using js and other content is preadded in html it's always gonna be the first child as you're using afterbegin or else you can do it like others gave you examples.
Sorry can't comment not enough reputation and recently joined
I need to be able to change out the css applied to the <body> on the fly. How, using javascript, could this be accomplished?
My css is stored as a string in a Javascript variable. I am not working with css files. The css consists of around 50 classes, so it doesn't make sense to apply them one-by-one. I know how this could be accomplished by changing the lowest class, but I'm just trying to see if it's possible to do using Javascript commands and variables.
Pseudo Code
var x = "#nav-bar-wrapper {
background-color: #4a3e7d;
padding: 20px 0;
}
#header-nav {
display: flex;
justify-content: center;
}...";
function changeCss() {
var el = $('myelement');
SomeJavaScriptFunction(el, x);
}
As #evolutionbox pointed out, it looks like you want to add new styles to the page. If so, just add them as text content in a style element:
const css = '#nav-bar-wrapper { ... }'
function changeCss() {
const el = document.createElement('style')
el.textContent = css
document.head.appendChild(el)
}
One easy way of doing it would be:
document.querySelector("yourElement").style.cssText += "Your super long string will go here and itll work"
Although, I dont think theres a way of giving different elements a uniqe style all in one line other than appending a style tag to the html. To use the method above, you'd have to separate #nav-bar-wrapper and #header-nav
Just keep in mind to use `` rather than "" to make the string go onto multiple lines
Here's a more JavaScript-y method than using hacky style tags.
const button = document.getElementById('button');
button.onclick = () => {
[
[ 'background', 'black' ],
[ 'color', 'white' ]
].map(([ prop, val ]) => {
button.style[prop] = val;
});
};
<button id="button">Hello there</button>
You could also try out https://cssinjs.org, which also works great in React.
Perhaps using jQuery's .css() function is worthy too: https://api.jquery.com/css/. It can take an object of CSS properties and apply them to an element.
$('#button').on('click', () => {
$('#button').css({ background: 'black', color: 'white' });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button id="button">Hi there</button>
You could also create a new style tag and append it to the body as many people have said. You can even append an external link rel="stylesheet" tag to the header to dynamically add a stylesheet from another URL! An alternative to this would be using the fetch API/jQuery AJAX/xmlhttprequest plus the code below:
$('#button').on('click', () => {
$('body').append('<style>#button { background: black; color: white; }</style>');
});
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button id="button">Hi there</button>
</body>
Another approach is using classes that you can dynamically add in JavaScript.
$('button').on('click', () => $('#button').addClass('clicked'));
.clicked {
background: black;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button id="button">Hi there</button>
You need to get a reference of your html element and after manipulate the DOM, here is an example:
document.getElementById('yourElementIdHere').style.color = 'red';
If you want to get your body reference to manipulate the DOM, you can do it. After this, you can change the style of your body using the style property, and use your string with your css.
document.querySelector("body").style = yourCssStringVar;
This link can help you, too:
JavaScript HTML DOM - Changing CSS
I'm making something for my own use that will allow me to quickly and easily stack commands (for Minecraft command block creations).
I have already created a button to create new textareas and a button to delete them. Presuming that there will be several textareas created, how could I delete a specific textbox in the middle of all of them (with the button to delete them)?
I have a div element to act as the parent, and actually was able to successfully delete the textareas AND buttons. My problem is after deleting even just one, I wasn't able to create more. And I noticed the text in the boxes would shift to the left.
The function :
function removeBox() {
var div = document.getElementById("newText");
var cats = document.getElementsByClassName("tAC");
var catss = document.getElementsByClassName("tACB");
div.removeChild(cats[0]);
div.removeChild(catss[0]);
}
Don't judge me because I named the variables cats!
The div :
<div id="newText">
<textarea class="tAC" id="firstText"></textarea>
<p></p>
</div>
Any ideas?
With what you have posted, I am suggesting this.
Whenever a new textarea is created, create a new button within the div that holds the textarea. This way when the remove button is clicked, you can use event.target to get the button element which dispatched the event and from there you can use event.target.previousSibling to find the textarea and remove it from the DOM by calling removeChild on event.target.parentNode. I am not sure if this is what you expect, so I didn't share code.
This is an example:
HTML:
<div id="container"></div>
JS:
var cont = document.getElementById("container");
cont.innerHTML += "<button id='b12' onclick='deleteMe("+'"b12"'+")'>b1b</button>"+
"<button id='b22' onclick='deleteMe("+'"b22"'+")'>b2b</button>"+
"<button id='b32' onclick='deleteMe("+'"b32"'+")'>b3b</button>";
window.deleteMe = function (elementId){
console.log("Borrando:", elementId );
document.getElementById(elementId).remove();
};
this is how it looks: fiddle
The idea is to be able to identify the element, that is why setting an id for the elements you need to manipulate is very helpful. Hope it inspire you.
I just tried your setup and it seems to be working fine:
function removeBox() {
var div = document.getElementById('new-text');
var cats = document.getElementsByClassName("tAC");
var catss = document.getElementsByClassName("tACB");
var cats0 = cats[0];
var catss0 = catss[0];
div.removeChild(cats0);
div.removeChild(catss0);
}
var button = document.getElementsByTagName('button')[0]
button.addEventListener('click',removeBox,false);
#new-text {
width: 200px;
}
#new-text p {
display: inline-block;
width: 100px;
}
#new-text .tAC {
float: left;
}
#new-text .tACB {
float: right;
}
button {
clear: both;
}
<div id="new-text">
<p class="tAC">cats0</p>
<p class="tACB">catss0</p>
<p class="tAC">cats1</p>
<p class="tACB">catss1</p>
<p class="tAC">cats2</p>
<p class="tACB">catss2</p>
</div>
<button type="button" />Click Me</button>
In css I have set all the <hr> elements in my html to "display:none;" which works.
I have an onclick event listener set up to change the "display" to "block".
I use:
document.getElementsByTagName("hr").innerHTML.style.display = "block";
I get an error "Cannot read property 'style' of undefined".
Do it the following way:
var hrItems = document.getElementsByTagName("hr");
for(var i = 0; i < hrItems.length; i++) {
hrItems[i].style.display = 'block';
}
This is incorrect in two ways
getElementsByTagName gives you a list on elements and there is no method to operate on all elements, so you'll have to loop through all of them and add the required style individually.
innerHTML returns a string containing the mark up in an element but <hr> doesn't have any thing in it and the style property is on the <hr> itself.
var hrs = document.getElementsByTagName("hr");
for(var i = 0; i < hrs.length; i++) {
hrs[i].style.display = 'block';
}
Simple (and very effective) solution:
tag your body with a class-element
<body class="no_hr"> <article><hr/> TEXT Foo</article> <hr/> </body>
in css don't hide hr directly, but do
.no_hr hr {
display:none;
}
now define a second style in your css
.block_hr hr{
display:block;
}
in your buttons onClick, change the one and only body class from no_hr to block_hr
onclick() {
if ( document.body.className == "no_hr" ) {
document.body.className = "block_hr";
} else {
document.body.className = "no_hr";
}
}
This is a very charming solution, because you don't have to iterate over elements yourself, but let your browsers optimized procedures do their job.
For people who want a solution that doesn't require JavaScript.
Create an invisible checkbox at the top of the document and make sure that people can click on it.
<input type="checkbox" id="ruler"/>
<label for="ruler">Click to show or hide the rules</label>
Then tell the stylesheet that the <hr>s should be hidden by default, but should be visible if the checkbox is checked.
#ruler, hr {display:none}
#ruler:checked ~ hr {display:block}
Done. See fiddle.
getElementsByTagName() returns a node list, and therefore you must iterate through all the results. Additionally, there is no innerHTML property of an <hr> tag, and the style must be set directly on the tag.
I like writing these types of iterations using Array.forEach() and call:
[].forEach.call(document.getElementsByTagName("hr"), function(item) {
item.style.display = "block";
});
Or, make it even easier on yourself and use jQuery:
$("hr").show();
I want my site title to display in a unique font from the rest of the content every time it appears in a heading, for branding reasons. For simplicity, let's pretend my special font is Courier and my company is called SparklePony. So, a line like,
<h1 class="title">SparklePony Board of Directors</h1>
would show a headline with the word SparklePony in Courier and Board of Directors in my site default font, Arial. (Yes, I know this would be hideous.)
I've tried using a jQuery string replacement, but I don't want to replace the string, I just want to see it in Courier (adding a class to just that word, or something of the like.) Replacing SparklePony with <span class="sparkle-pony">SparklePony</span> caused the whole ugly string with tags and everything to show on my site, rather than adding the class.
Am I doing something wrong with my string replace, or is there a better way to style all occurrences of a string?
You can do it like this - specifying the selector you want - #('h1') or by class.
$('.title').html(function(i,v){
return v.replace(/SparklePony/g,'<span class="sparkle">SparklePony</span>');
});
http://jsfiddle.net/cQjsu/
Without seeing the code (which would be kinda important in questions like this), best guess is that you're using .text() instead of .html() which would parse the HTML correctly.
It could do with some tidying, but this may be a good starting point: http://jsfiddle.net/c24w/Fznh4/9/.
HTML
<div id="title">Highlight this blah blah HiGhLiGhT THIS blah</div>
<button id="clickme">Click to highlight text</button>
CSS
#title{
font-family: sans-serif;
font-size: 20pt;
margin: 30px 0;
}
span.highlight{
color: #09f;
font-weight: bold;
}
JavaScript
function highlightText(element, phrase, allOccurrences, caseSensitive){
var modifiers = (allOccurrences ? 'g' : '') + (caseSensitive ? '' : 'i');
var text = element.innerHTML;
element.innerHTML = text.replace(new RegExp(phrase, modifiers), function(match){
return '<span class="highlight">' + match + '</span>';
});
}
var button = document.getElementById('clickme');
var el = document.getElementById('title');
button.onclick = function(){
highlightText(el, 'highlight this', true, false);
button.onclick = null;
};
Try Something like that :
$.each($(".title"),function({
$(this).html($(this).html().replace("SparklePony","<span class='sparkle-pony'>SparklePony</span>"))
});
Nice and short:
var $body = $("body");
$body.html($body.html().replace(/SparklePony/ig, "<span class='cool'>SparklePony</span>"));
But keep in mind that $("body") is a very costly selector. You should consider a more precise parent target.
Demo here (fiddle)