Set div class to match its text - javascript

I want to copy the text of a div to its class. I have got the code below but it copies text from all sibling div(s) but I want only current div's text to be its class.
Like the code below will copy "I am alex How are you" as a class for both divs below code, what I want the 1st div should only have class "I am alex" and likewise next class should only have a class "How are you" .
<div class="someText">I am alex</div>
<div class="someText">How are you</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js" type="text/javascript"></script>
<script>
var classes = $(".someText").text().replace(/[, -- .]/g," ");
$(".someText").addClass(classes);
</script>

It's a very odd requirement, but you can achieve it by passing a function to addClass(), like this:
$('.someText').addClass(function() {
return $(this).text();
});
.am {
color: blue;
}
.are {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="someText">I am alex</div>
<div class="someText">How are you</div>

You would need to loop through each div.
$(function() {
$('div.someText').each(function() {
var classes = $(this).text().replace(/[, -- .]/g, " ");
$(this).addClass(classes);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="someText">I am alex</div>
<div class="someText">How are you</div>

This what you wanted?
var divs = $(".someText");
for (var i = 0; i < divs.length; i++) {
$(divs[i]).addClass($(divs[i]).text().replace(/[, -- .]/g," "));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="someText">I am alex</div>
<div class="someText">How are you</div>

Related

Javascript: replace text inside <div>foo <span>text </span>bar</div> by <div>foo text bar</div>

Just as the title suggests, lets consider the following html snippet:
<html>
<body>
<div>foo <span>text </span>bar</div>
</body>
</html>
I would like to transform it by removing the span tags, but keeping the text they contain in the same location, such as
<html>
<body>
<div>foo text bar</div>
</body>
</html>
I would like to do that in javascript. Because this task is (I suppose) uncommon (I am in fact trying to build a GUI for marking data for NLP) I could not really find a solution browsing SO or Google... And I am very new to javascript so I didn't really know where to start.
Aditional question:
If one know how to resolve the first question, maybe can quickly mention how to perform the same transformation on all document span, such as the following document:
<html>
<body>
<div>foo <span>text </span>bar</div>
<div>foo1 <span>text1 </span>bar1</div>
</body>
</html>
becomes
<html>
<body>
<div>foo text bar</div>
<div>foo1 text1 bar1</div>
</body>
</html>
Thx
You can change the outerHTML of <span> to its innerHTML
var elms = document.querySelectorAll('div *');
elms.forEach(e => e.outerHTML = ` ${e.innerHTML} `)
//just to test the effect.
document.querySelectorAll('div').forEach(x => console.log(x.outerHTML))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>foo<span>text</span>bar</div>
<div>foo1<span>text1</span>bar1</div>
Use replace:
let div = document.getElementById("myDiv");
div.innerHTML = div.innerHTML.replace("<span>", " ").replace("</span>", " ");
span {
color: red;
}
<div id="myDiv">foo<span>text</span>bar</div>
You can do like this
$(document).ready(function(){
$("div").each(function(index,item){
$(item).html($(item).html().replace(/<\/?span[^>]*>/g,""));
})
})
$(document).ready(function(){
$("div").each(function(index,item){
$(item).html($(item).html().replace(/<\/?span[^>]*>/g,""));
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>foo <span>text</span> bar</div>
<div>foo1 <span>text1</span> bar1</div>
Simplest way would be to change innerHtml to innerText (if you want to get rid of all inner tags):
var divs = document.querySelectorAll('div');
for (i = 0; i < divs.length; i++) {
divs[i].innerHTML = divs[i].innerText;
}
span {color:red;}
<div>foo <span>text </span>bar</div>
<div>foo1 <span>text1 </span>bar1</div>

For loop not working two id plus variable

Hi there I am trying to make this for loop
<script>
$(document).ready(function(){
sizeNestable();
});
for (p = 1; p <= 20; p++) {
$('#nestable'+p+', #nestable'+(p+1)).change(function() {
sizeNestable();
});
function sizeNestable() {
var n3 = $('#nestable3').find('.dd3-handle').height('100%');
var n4 = $('#nestable4').find('.dd3-handle').height('100%');
}
}
</script>
So what I need is
$('#nestable1, #nestable2').change(function() {
and
var n3 = $('#nestable1).find('.dd3-handle').height('100%');
and then to increase for one ..
What I am doing wrong here?
I don't understand what you are trying to do exactly. But there are a few errors I see.
function sizeNestable does not belong inside a for-loop. Instead you should give the function a parameter, you should call that function inside the loop and pass p (or something else) as a parameter.
Your for-loop is not inside a function, yet it contains HTML elements. This must be avoided.
You should keep away from HTML elements, until document.ready . It's okay to have HTML inside a function, because a function is only executed when you call it. Your for-loop is executed as soon as the script is loaded, and the HTML might not be ready yet.
My code contains the pieces of your code, please explain what you are trying to do. Which kind of HTML elements are you talking about?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
for (var p = 1; p <= 20; p++) {
var selector = '#nestable' + p ;
$(selector).click(function() {
sizeNestable(this); // inside this kind of function (triggered by an event) 'this' is whatever was triggered (in this case clicked on)
});
}
});
function sizeNestable(element) {
$(element).find('.dd3-handle').css('height', '100%');
}
</script>
<style>
.mydiv {
height: 20px;
}
.dd3-handle {
height: 3px;
overflow: hidden;
float: left;
}
</style>
<div class="mydiv" id="nestable1">Hello <div class="dd3-handle">|||</div> </div>
<div class="mydiv" id="nestable2">World <div class="dd3-handle">|||</div> </div>
<div class="mydiv" id="nestable3">! <div class="dd3-handle">|||</div> </div>
<div class="mydiv" id="nestable4">foo <div class="dd3-handle">|||</div> </div>
<div class="mydiv" id="nestable5">bar <div class="dd3-handle">|||</div> </div>
<hr/>
<p>Click on one of the lines above. hidden ||| elements will appear</p>

document.getElementById("xxx").style [duplicate]

This question already has answers here:
How to apply CSS style to all elements with same ID using one button?
(6 answers)
Closed 6 years ago.
I want to use getElementById("xxx").style.color = "xxx".
With this I want to change some css value. But the problem is when i use this and test all same id with this but it does't effect all id and effects only the first one.
Sample code is as follow:
<html>
<body>
<div id = "test">Test</div>
<div id = "test">Test</div>
<div id = "test">Test</div>
<div id = "test">Test</div>
<script>
document.getElementById("test").style.color = "blue"
</script>
</body>
</html>
What should i do to change all 4 Test to color blue.
AnyIdea pls.
Thanks
An ID must be unique in an HTML document. Write valid HTML.
To represent multiple, related elements: use a class.
You can then use getElementsByClassName or querySelectorAll to get an array-like object which you can use a for loop to access each element in turn.
var elements = document.querySelectorAll(".test");
for (var i = 0; i < elements.length; i++) {
elements[i].style.color = "blue";
}
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
Alternatively, write a stylesheet with a descendant combinator and toggle the classes on a containing element.
document.getElementById("container").classList.add("foo");
.test { color: black; }
.foo .test { color: blue; }
<div id="container">
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
</div>
As stated before, an ID must be unique. If you want to give multiple DOM-elements the same style just use 'class'.
you could try this:
<html>
<body>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<script>
var divList = document.getElementsByClassName("test");
for (var i = 0; i < divList.length; i++) {
divList[i].style.color = "red";
}
</script>
</body>
</html>
to change the style using javascript.
There are two problems with your code :
id must be unique, so you should use eg. class instead
you should loop across the different elements that are selected
This is my prefered way to correct those two problems :
<html>
<body>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<script>
Array.prototype.slice.call(
document.getElementsByClassName("test")
).forEach(function(element) {
element.style.color = "blue"
});
</script>
</body>
</html>
See also this Fiddle.
For jQuery Solution
You cannot use same id for performing same operation on all the elements
You can use class name and add style using jquery like
$(".className").css("color","blue");

How to use .after() as .html() if element exists?

Here is my code:
$('button').on('click', function(){
$('div').after('<p>this element should be unique</p>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>this is a div</div>
<button>click</button>
As you see, when I click on that <button> several times, I will see multiple element which have created, like this:
<div>this is a div</div>
<p>this element should be unique</p>
<p>this element should be unique</p>
<p>this element should be unique</p>
<button>click</button>
but I want to append that <p> after <div> only if it isn't exist, otherwise I want to replace it. Anyway I want this output: (both for one time clicking and multiple times clicking)
<div>this is a div</div>
<p>this element should be unique</p>
<button>click</button>
How can I do that?
If you will have only one p
edited
$('button').on('click', function() {
if (!($('div').next('p').length)) {
$('div').after('<p>this element should be unique</p>');
}else{
$('div').next('p').html('this will replace');
}
});
You can check to see if the element exists, and if it does update the content. Something like this should work:
var index = 0;
$('button').on('click', function(){
index++;
if($('#myWrapper').length == 0) {
$('div').after('<p id="myWrapper">this element should be unique' + index +'</p>');
} else {
$('#myWrapper').html('<p>this element should be unique' + index +'</p>');
}
});
JS Fiddle example: https://jsfiddle.net/igor_9000/44mgz316/3/
Hope that helps!
Without knowing how you're generating that <p> elements, here you can check some generic solution, and implement your own logic
var text;
$('#text').on('change', function() {
text = $(this).val();
});
$('button').on('click', function() {
if ($('div').next('p:contains(' + text + ')').length) {
} else {
$('div').next('p').remove();
$('div').after('<p>' + text + '</p>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text">
<div>this is a div</div>
<button>click</button>
Better add a wrapper, and just replace its contents:
var $target = null;
$('button').on('click', function(){
if(!$target) $target = $('<div></div>').insertAfter('div');
$target.html('<p>this element should be unique</p>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>this is a div</div>
<button>click</button>

How to use JavaScript to change div backgroundColor

The HTML below:
<div id="category">
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
</div>
When mouseover the content of div then it's backgroundColor and the h2 (inside this div) backgroundColor change (just like the CSS: hover)
I know this can use CSS (: hover) to do this in modern browser but IE6 doesn't work.
How to use JavaScript (not jQuery or other JS framework) to do this?
Edit:how to change the h2 backgroundColor too
var div = document.getElementById( 'div_id' );
div.onmouseover = function() {
this.style.backgroundColor = 'green';
var h2s = this.getElementsByTagName( 'h2' );
h2s[0].style.backgroundColor = 'blue';
};
div.onmouseout = function() {
this.style.backgroundColor = 'transparent';
var h2s = this.getElementsByTagName( 'h2' );
h2s[0].style.backgroundColor = 'transparent';
};
Adding/changing style of the elements in code is a bad practice. Today you want to change the background color and tomorrow you would like to change background image and after tomorrow you decided that it would be also nice to change the border.
Editing the code every-time only because the design requirements changes is a pain. Also, if your project will grow, changing js files will be even more pain. More code, more pain.
Try to eliminate use of hard coded styles, this will save you time and, if you do it right, you could ask to do the "change-color" task to someone else.
So, instead of changing direct properties of style, you can add/remove CSS classes on nodes. In your specific case, you only need to do this for parent node - "div" and then, style the subnodes through CSS. So no need to apply specific style property to DIV and to H2.
One more recommendation point. Try not to connect nodes hardcoded, but use some semantic to do that. For example: "To add events to all nodes which have class 'content'.
In conclusion, here is the code which I would use for such tasks:
//for adding a css class
function onOver(node){
node.className = node.className + ' Hover';
}
//for removing a css class
function onOut(node){
node.className = node.className.replace('Hover','');
}
function connect(node,event,fnc){
if(node.addEventListener){
node.addEventListener(event.substring(2,event.length),function(){
fnc(node);
},false);
}else if(node.attachEvent){
node.attachEvent(event,function(){
fnc(node);
});
}
}
// run this one when window is loaded
var divs = document.getElementsByTagName("div");
for(var i=0,div;div =divs[i];i++){
if(div.className.match('content')){
connect(div,'onmouseover',onOver);
connect(div,'onmouseout',onOut);
}
}
And you CSS whould be like this:
.content {
background-color: blue;
}
.content.Hover{
background-color: red;
}
.content.Hover h2{
background-color : yellow;
}
Access the element you want to change via the DOM, for example with document.getElementById() or via this in your event handler, and change the style in that element:
document.getElementById("MyHeader").style.backgroundColor='red';
EDIT
You can use getElementsByTagName too, (untested) example:
function colorElementAndH2(elem, colorElem, colorH2) {
// change element background color
elem.style.backgroundColor = colorElem;
// color first contained h2
var h2s = elem.getElementsByTagName("h2");
if (h2s.length > 0)
{
hs2[0].style.backgroundColor = colorH2;
}
}
// add event handlers when complete document has been loaded
window.onload = function() {
// add to _all_ divs (not sure if this is what you want though)
var elems = document.getElementsByTagName("div");
for(i = 0; i < elems.length; ++i)
{
elems[i].onmouseover = function() { colorElementAndH2(this, 'red', 'blue'); }
elems[i].onmouseout = function() { colorElementAndH2(this, 'transparent', 'transparent'); }
}
}
<script type="text/javascript">
function enter(elem){
elem.style.backgroundColor = '#FF0000';
}
function leave(elem){
elem.style.backgroundColor = '#FFFFFF';
}
</script>
<div onmouseover="enter(this)" onmouseout="leave(this)">
Some Text
</div>
It's very simple just use a function on javaScript and call it onclick
<script type="text/javascript">
function change()
{
document.getElementById("catestory").style.backgroundColor="#666666";
}
</script>
Change Bacckground Color
This one might be a bit weird because I am really not a serious programmer and I am discovering things in programming the way penicillin was invented - sheer accident. So how to change an element on mouseover? Use the :hover attribute just like with a elements.
Example:
div.classname:hover
{
background-color: black;
}
This changes any div with the class classname to have a black background on mousover. You can basically change any attribute. Tested in IE and Firefox
Happy programming!
If you are willing to insert non-semantic nodes into your document, you can do this in a CSS-only IE-compatible manner by wrapping your divs in fake A tags.
<style type="text/css">
.content {
background: #ccc;
}
.fakeLink { /* This is to make the link not look like one */
cursor: default;
text-decoration: none;
color: #000;
}
a.fakeLink:hover .content {
background: #000;
color: #fff;
}
</style>
<div id="catestory">
<a href="#" onclick="return false();" class="fakeLink">
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
</a>
<a href="#" onclick="return false();" class="fakeLink">
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
</a>
<a href="#" onclick="return false();" class="fakeLink">
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
</a>
</div>
To do this without jQuery or any other library, you'll need to attach onMouseOver and onMouseOut events to each div and change the style in the event handlers.
For example:
var category = document.getElementById("catestory");
for (var child = category.firstChild; child != null; child = child.nextSibling) {
if (child.nodeType == 1 && child.className == "content") {
child.onmouseover = function() {
this.style.backgroundColor = "#FF0000";
}
child.onmouseout = function() {
// Set to transparent to let the original background show through.
this.style.backgroundColor = "transparent";
}
}
}
If your h2 has not set its own background, the div background will show through and color it too.
You can try this script. :)
<html>
<head>
<title>Div BG color</title>
<script type="text/javascript">
function Off(idecko)
{
document.getElementById(idecko).style.background="rgba(0,0,0,0)"; <!--- Default --->
}
function cOn(idecko)
{
document.getElementById(idecko).style.background="rgb(0,60,255)"; <!--- New content color --->
}
function hOn(idecko)
{
document.getElementById(idecko).style.background="rgb(60,255,0)"; <!--- New h2 color --->
}
</script>
</head>
<body>
<div id="catestory">
<div class="content" id="myid1" onmouseover="cOn('myid1'); hOn('h21')" onmouseout="Off('myid1'); Off('h21')">
<h2 id="h21">some title here</h2>
<p>some content here</p>
</div>
<div class="content" id="myid2" onmouseover="cOn('myid2'); hOn('h22')" onmouseout="Off('myid2'); Off('h22')">
<h2 id="h22">some title here</h2>
<p>some content here</p>
</div>
<div class="content" id="myid3" onmouseover="cOn('myid3'); hOn('h23')" onmouseout="Off('myid3'); Off('h23')">
<h2 id="h23">some title here</h2>
<p>some content here</p>
</div>
</div>
</body>
<html>

Categories