Can I use different styles within one div - html

I'm using a script to do a mouseover effect with images and also highlighting text in a different color using the getElementById phrase. I understand that an ID can only be used once, and if it needs to be used more than once I should use class. But there is no getElementByClass function. I have 2 areas of type that I want to highlight, one is centered, the other is left justified. Is there a way to use the same id for both styles?
<div id="georgia">
<style="text-align: center;">
<strong>Headquarters:
</strong>
</style>more text here
</div>
This is the script I am using:
<script type="text/javascript">// < ![CDATA[
function on(el) {
if (document.getElementById(el)) {
document.getElementById(el).style.color="green";
};
};
function off(el) {
if (document.getElementById(el)) {
document.getElementById(el).style.color="";
};
};
// ]]></script>
So what you are saying is I can replace the getElementById with getElementByClassName then it will work?
This is the format I'm using, the first part of the text (Headquarters) is not showing up, but the second part (more text here) is fine.

You need to use document.getElementsByClassName, which returns a list of the objects with that class name:
var all = document.getElementsByClassName("bar");
for(var i = 0; i < all.length; i++){
var obj = all[i];
obj.style.fontWeight = 'bold';
}
<div id="foo" class="bar">hi</div>
<div class="bar">bye</div>
<div id="bar">sup</div>

Related

Using jquery to have one html element point to another

I am new to jquery and was wondering how I can point one html element equal to another. I want to make it so that whenever something in the h2 tag changes, the text within the p tags will copy the change. Below is how my tags are set up within the class fc-center.
var title = $('div.fc-center h2').text();
$('.fc-center').append('<p>'+'' +'</p>');
with the html looking something like
<div class = 'fc-center'>
<h2> text text</h2>
<p> </p>
</div>
essentially what I want to do is something like this :
$('div.fc-center p').equalto $('div.fc-center h2')
But I am not quite sure how to go about it
I propose this solution:
var title = $('.fc-center').find('h2').text();
var elementsP=$('.fc-center').find('p');
if (elementsP.length > 0) {
$.each(elementsP, function(i, val) {
$(this).empty().html(title);
});
}
https://jsfiddle.net/julian9319/grc0y6qf/1/

Using array values to assign button labels in HTML

I'm trying to create an add-on on for gSheets to display a sidebar or dialog with a dynamic number of buttons derived from text in a cell which has been clicked on.
There is a varying number of words in the cells of the target column. The objective is to load the words into a single-dimensional array and use each word as the label of a button. Then by clicking on a button, the same text appearing as the button label is copied to the clipboard.
I've successfully gotten the contents of a selected cell to load into an array as follows (the target strings are delimited by a period):
function splitText() {
var array1 = [{}];
var string1 = SpreadsheetApp.getActiveRange().getValue();
array1 = string1.split('. ');
for(var i=0; i<array1.length; i++){
array1[i] = '\\n'+'\\n'+array1[i];
}
Including custom buttons in a sidebar requires referencing an HTML file which I'm doing as follows:
function openSidebar(){
var html = HtmlService.createHtmlOutputFromFile('Sidebar').setTitle('Text Copy Buttons');
SpreadsheetApp.getUi().showSidebar(html);
}
I'm familiar with the basic HTML to create a button as follows:
<body>
<button onclick='myFunction()' id='button1'>LABEL TO BE ASSIGNED</button>
</body>
I'd like to know how to create a variable number of buttons by looping through the array and assigning each array value to a new button label. Any suggestions much appreciated!
You can try jQuery:
Flow:
Serve basic HTML with buttons inside a div
On Window Load run splitText function on server side with google.script.run
Receive the array from splitText and update div with jQuery append
Alternatively, You can directly use Templated HTML to do a for-loop to append.
Index.html:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function(){
google.script.run.withSuccessHandler(showButtons)
.splitText()
});
function showButtons(arr){
var b = $('#buttons');
b.empty();
for (var i=0;i<arr.length;i++){
b.append("<button onclick='myFunction()' id='button"+i+"'>"+arr[i]+"</button>")
}
}
</script>
</head>
<body>
<div id ="buttons">
<button onclick='myFunction()' id='button'>LABEL TO BE ASSIGNED</button>
</div>
</body>
Code.gs:
function splitText() {
return SpreadsheetApp.getActiveRange().getValue()
.toString()
.split('. ');
}
References:
TemplatedHTML
jQuery vs Template

Accessing the text of a class that contains other elements using Cheerio

I only want to access h1's text (H1 title is here in this case), but it prints everything. I tried adding .remove('.small-title') before text(), but it didn't work.
<div class="modal-know>
<h1>
H1 title is here
<div class="small-title">
Click
Click 2
</div>
</h1>
</div>
Node.js code
var newsTitle = $2('.modal-know h1').text(); // prints out everything
console.log(newsTitle);
have a look at cheerio docs: text()
it says
including their descendants
That is the same behaviour that jQuery .text()
So maybe this answer could help you :jQuery: using .text() to retrieve only text not nested in child tags
Here you have the code I tested:
let newsTitle = $('.modal-know h1').contents()[0].nodeValue;
// solution 2:
// .clone() //clone the element
// .children() //select all the children
// .remove() //remove all the children
// .end() //again go back to selected element
// .text(); // prints out everything
//solution 3:
// .contents().filter(function(){
// return this.nodeType == 3;
// })[0].nodeValue;
console.log(newsTitle);
*in your code sample ther is a missing " in the div modal-know class
<div class="modal-know> -> <div class="modal-know">

Create div and add style

I have one big div with id="elements" and I load from JSON file new elements objects and I need that for every element create new div inside elements ( elements div should contain lot off smaller divs, for every element one small div ). How to place this small divs inside this big div one behind another ? How to add this small divs a class style ?
In Dojo (since you have the dojo tag):
var div_elements = dojo.byId("elements");
dojo.forEach(json_data.items, function(item) {
dojo.create("div", { "class":"whatever " + item.classNames }, div_elements);
});
Of course, you can put anything as the class for your div. I just provided an example. In the second argument to dojo.create, you pass in a hash containing all the properties you want that div to have.
Create a new DOM element like so:
var childDiv = document.createElement('div');
Then add to the outer div like so:
var insertedElement = div.insertBefore(childDiv, null);
You would then keep creating childDivs as you iterate over your JSON data, and inserting them into the div Node as above.
I think you need something like this:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function(){
json_data = 'Hey';
$('#elements').append('<div class="in_elements">' + json_data + '</div>');
});
</script>
<div id="elements">
</div>
Test it
There a simple jQuery functions for that:
var box= $("#elements");
// create elements
for (var i=0; i<items.length; i++) {
var t = $("<div class=\"element\" id=\"item_"+i+"\">"+items[i]['text']+"</div>");
box.append(t);
}
That's what you where looking for?

highlight word in div using javascript

hi i have to implement find and replace functionality in my project. in this functionality there is one find and replace button on the top of contenteditable div. when user click on this button, popup window will open and ask for the search word when specify word and press find it will find word in that div only. and if match found it will highlight that word. so anybody tell me how can i highlight word in div. its urgent so please . thank you.
<div id="test" contenteditable="true">
this is test <font class='classname'> some text test</font>
</div>
i want to high light only test word not else
You will need to search through the div to find the word and then put that word into a span, and change the background color of the span.
Edit: I just noticed that you are not using CSS, so you will need to insert a font tag to change the color.
I just stole this from Sphix, the documentation tool:
/**
* highlight a given string on a jquery object by wrapping it in
* span elements with the given class name.
*/
jQuery.fn.highlightText = function(text, className) {
function highlight(node) {
if (node.nodeType == 3) {
var val = node.nodeValue;
var pos = val.toLowerCase().indexOf(text);
if (pos >= 0 && !jQuery.className.has(node.parentNode, className)) {
var span = document.createElement("span");
span.className = className;
span.appendChild(document.createTextNode(val.substr(pos, text.length)));
node.parentNode.insertBefore(span, node.parentNode.insertBefore(
document.createTextNode(val.substr(pos + text.length)),
node.nextSibling));
node.nodeValue = val.substr(0, pos);
}
}
else if (!jQuery(node).is("button, select, textarea")) {
jQuery.each(node.childNodes, function() {
highlight(this)
});
}
}
return this.each(function() {
highlight(this);
});
}
/**
* helper function to hide the search marks again
*/
hideSearchWords : function() {
$('.sidebar .this-page-menu li.highlight-link').fadeOut(300);
$('span.highlight').removeClass('highlight');
},
/**
* highlight the search words provided in the url in the text
*/
highlightSearchWords : function() {
var params = $.getQueryParameters();
var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : [];
if (terms.length) {
var body = $('div.body');
window.setTimeout(function() {
$.each(terms, function() {
body.highlightText(this.toLowerCase(), 'highlight');
});
}, 10);
$('<li class="highlight-link"><a href="javascript:Documentation.' +
'hideSearchWords()">' + _('Hide Search Matches') + '</a></li>')
.appendTo($('.sidebar .this-page-menu'));
}
},
So, adding this to a js file in your site, any page with it that receives a highlight GET parameter will search and highlight the word in the page.
You can find a demo of the working code in:
http://sphinx.pocoo.org/intro.html?highlight=python
Note: This code needs jQuery, off course...
Its actually pretty easy using the prototype library:
<html>
<head>
<style type="text/css">
#content span {
background-color: yellow;
}
</style>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
Event.observe(window,'load',function(){
var htm = $('content').innerHTML;
$('content').innerHTML = htm.sub('my','<span>my</span>');
});
</script>
</head>
<body>
<div id="content">
This is the div containing my content.
</div>
</body>
</html>
This should get you started so you can implement the rest.
To highlight a word you have to select it somehow. One option is to surround the word with a span tag.
this is <span class="highlight">test</span> some text test
then specify CSS for the highlight class.