Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

108
Vistas
¿Cómo puedo cambiar el estilo de todos los <mark>snippets</mark> dentro de html usando javascript?

Tengo un archivo html estático que contiene principalmente texto. Muchos fragmentos de texto se resaltan con la etiqueta <mark> . Me gustaría agregar un botón que alterne el peso del texto de los fragmentos de texto marcados entre negrita y normal. El efecto buscado es encender/apagar el resaltado.

¿Hay alguna forma mágica de hacerlo cambiando directamente el estilo de la clase mark css?

Ejemplo:

  • HTML: ... This is an <mark>important text snippet</mark> ...
  • Clase CSS ANTES de presionar el botón: mark { text-weight: bold; }
  • Clase CSS DESPUÉS de presionar el botón: mark { text-weight: normal; }

La razón por la que quiero hacer esto es permitir que el usuario decida si quiere ver el texto resaltado o no. Sé que puedo cambiar el estilo de cada fragmento de texto marcado, pero me pregunto si hay una forma más directa.

almost 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Método 1: alternar una clase en un elemento principal

Una forma más directa sería agregar una clase a un elemento principal . Luego, en CSS, puede seleccionar todos los elementos de mark secundarias. Este método le evita iterar sobre cada elemento de marca en su página en JS. Puede agregar esta clase en un div contenedor o incluso en el elemento html raíz si lo desea.

classList.toggle es compatible con todos los principales navegadores: https://caniuse.com/?search=classlist.toggle

 function toggleMarkup() {
 document.querySelector("#content").classList.toggle("markup-shown");
}
 p.markup-shown mark {
 font-weight: bold;
}
 <p id="content">
Hello! This is some <mark>marked up</mark> text! And this is some more <mark>marked</mark> text.
</p>

<button onclick="toggleMarkup()">
Click me to toggle markup.
</button>

Método 2 - Usando CSSOM

https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model https://stackoverflow.com/a/55468693/9627251

También puede obtener y modificar clases CSS existentes directamente desde JS:

 const rules = document.styleSheets.map(sheet => sheet.cssRules);
const rule = rules.find(r => r.selectorText == 'mark');
rule.style.fontWeight = 'bold'; // or normal, in your toggle function logic

Tenga en cuenta que ya debería tener una regla CSS como:

 mark { font-weight: normal; }
almost 4 years ago · Santiago Trujillo Denunciar

0

Consulte todos sus elementos de mark , luego cambie una clase de resaltado para afectar su estilo de peso de fuente. Obtenga los padres de los elementos de marca usando '.closest()' y agregue un botón a cada elemento padre.

 const marks = document.querySelectorAll('mark')

// use event target to get the parent element and subsequent 
// mark element and toggle a class of normal font weight
function toggleHighlight(e) {
 e.target.closest('li').querySelectorAll('mark').forEach( el => {
 el.classList.toggle('normal')
 })
}

marks.forEach(mark => {
 // create the button
 const button = document.createElement('button')
 // add text for the button
 button.textContent = 'Toggle Highlight'
 // get the parent element your mark is living within and append the button to it
 // make sure it only gets one button in case there are more than one mark element
 !mark.parentNode.innerHTML.includes('button') ? mark.parentNode.appendChild(button) : null 
 // event listener for when the button is pressed 
 button.addEventListener('click', toggleHighlight)
})
 mark {
 font-weight: bold;
}

.normal {
 font-weight: normal;
}

li {
 clear: left;
}

button {
 float: right;
}
 <ul>
 <li>This is not important text</li><hr>
 <li><mark>This text here important text.</mark> But this is not. <mark>We have more important text here as well.</mark> Arcu cursus euismod quis viverra nibh cras pulvinar mattis. Tristique et egestas quis ipsum suspendisse ultrices gravida dictum. Ac turpis egestas integer eget. </li><hr>
 <li>This is text not important text. <mark>But this is</mark></li><hr>
 <li><mark>This text here important text.</mark> But this is not</li><hr>
</ul>

almost 4 years ago · Santiago Trujillo Denunciar

0

¿Qué pasa con algo como esto?

 <html>
 <head>
 <style>
 mark {
 font-weight: bold;
 background: none;
 }
 </style>
 </head>
<body>

This is an <mark>important text snippet</mark> and so <mark>is this</mark>.

<button onclick = "changeMark()">Change Mark Style</button>

<script>
 function changeMark() {
 document.querySelectorAll("mark").forEach(e => e.style.fontWeight = "normal");
 }
</script>

</body>
</html>
almost 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda